Agent Skills › staskh/trading_skills

staskh/trading_skills

GitHub

获取股票 upcoming 财报日期、交易时段及 EPS 预估。支持单个或多个代码查询,按日期排序输出,适用于评估持仓风险、规划交易及构建观察列表。

28 skills 288

Install All Skills

npx skills add staskh/trading_skills --all -g -y
More Options

List skills in collection

npx skills add staskh/trading_skills --list

Skills in Collection (28)

获取股票 upcoming 财报日期、交易时段及 EPS 预估。支持单个或多个代码查询,按日期排序输出,适用于评估持仓风险、规划交易及构建观察列表。
查询某公司或股票的下次财报发布日期 查看财报日历或 earnings calendar 询问特定股票何时发布财报 检查投资组合的财报风险
.claude/skills/earnings-calendar/SKILL.md
npx skills add staskh/trading_skills --skill earnings-calendar -g -y
SKILL.md
Frontmatter
{
    "name": "earnings-calendar",
    "description": "Get upcoming earnings dates with timing (before\/after market) and EPS estimates. Use when user asks about earnings dates, earnings calendar, when a company reports, or upcoming earnings.",
    "dependencies": [
        "trading-skills"
    ]
}

Earnings Calendar

Retrieve upcoming earnings dates for stocks.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/earnings.py SYMBOLS

Arguments

  • SYMBOLS - Ticker symbol or comma-separated list (e.g., AAPL or AAPL,MSFT,GOOGL,NVDA)

Output

Single symbol returns:

  • symbol - Ticker symbol
  • earnings_date - Next earnings date (YYYY-MM-DD)
  • timing - "BMO" (Before Market Open), "AMC" (After Market Close), or null
  • eps_estimate - Consensus EPS estimate, or null if unavailable

Multiple symbols returns:

  • results - Array of earnings info, sorted by date (soonest first)

Examples

# Single symbol
uv run python scripts/earnings.py NVDA

# Multiple symbols (sorted by date)
uv run python scripts/earnings.py AAPL,MSFT,GOOGL,NVDA,META

# Portfolio earnings calendar
uv run python scripts/earnings.py CAT,GOOG,HOOD,IWM,NVDA,PLTR,QQQ,UNH

Use Cases

  • Check when positions have upcoming earnings risk
  • Plan trades around earnings announcements
  • Build an earnings calendar for watchlist

Dependencies

  • pandas
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
获取Yahoo Finance基本面数据,包括财务、收益和关键指标。支持计算Piotroski F-Score以评估公司财务健康度,涵盖9项标准及评分解读,辅助价值投资和财务强度分析。
查询财务数据 获取收益信息 查看关键指标 计算Piotroski F-Score 评估财务健康度
.claude/skills/fundamentals/SKILL.md
npx skills add staskh/trading_skills --skill fundamentals -g -y
SKILL.md
Frontmatter
{
    "name": "fundamentals",
    "description": "Get fundamental financial data including financials, earnings, and key metrics. Use when user asks about financials, earnings, revenue, profit, balance sheet, income statement, or company fundamentals.",
    "dependencies": [
        "trading-skills"
    ]
}

Fundamentals

Fetch fundamental financial data from Yahoo Finance.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/fundamentals.py SYMBOL [--type TYPE]

Arguments

  • SYMBOL - Ticker symbol
  • --type - Data type: all, financials, earnings, info (default: all)

Output

Returns JSON with:

  • info - Key metrics (market cap, PE, EPS, dividend, etc.)
  • financials - Recent quarterly/annual income statement data
  • earnings - Historical and estimated earnings

Present key metrics clearly. Compare actual vs estimated earnings if relevant.


Piotroski F-Score

Calculate Piotroski's F-Score to evaluate a company's financial strength using 9 fundamental criteria.

Instructions

uv run python scripts/piotroski.py SYMBOL

What is Piotroski F-Score?

Piotroski's F-Score is a fundamental analysis tool developed by Joseph Piotroski that evaluates a company's financial strength using 9 criteria. Each criterion scores 1 point if passed, 0 if failed, for a maximum score of 9.

The 9 Criteria

  1. Positive Net Income - Company is profitable
  2. Positive ROA - Assets are generating returns
  3. Positive Operating Cash Flow - Company generates cash from operations
  4. Cash Flow > Net Income - High-quality earnings (cash exceeds accounting profit)
  5. Lower Long-Term Debt - Decreasing leverage (improving financial position)
  6. Higher Current Ratio - Improving liquidity
  7. No New Shares Issued - No dilution (or share buybacks)
  8. Higher Gross Margin - Improving profitability efficiency
  9. Higher Asset Turnover - More efficient use of assets

Score Interpretation

  • 8-9: Excellent - Very strong financial health
  • 6-7: Good - Strong financial health
  • 4-5: Fair - Moderate financial health
  • 0-3: Poor - Weak financial health

Output

Returns JSON with:

  • score - F-Score (0-9)
  • max_score - Maximum possible score (9)
  • criteria - Detailed breakdown of each criterion with pass/fail status and values
  • interpretation - Text description of financial health level
  • data_available - Boolean indicating if year-over-year comparison data is available for criteria 5-9

Implementation Details

  • Criteria 1-4 use quarterly financial data (most recent year)
  • Criteria 5-9 use annual financial data for year-over-year comparisons
  • Compares most recent fiscal year vs previous fiscal year

Use Cases

Use Piotroski F-Score when:

  • Evaluating fundamental financial strength
  • Screening for value stocks with improving fundamentals
  • Assessing financial health trends
  • Comparing financial strength across companies
  • Identifying companies with strong fundamentals but undervalued prices

Dependencies

  • pandas
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
基于Black-Scholes模型计算期权希腊字母(Delta、Gamma等)及隐含波动率。支持指定标的价格、行权价、到期日及市场报价,通过Newton-Raphson算法反推IV,并输出JSON格式结果及术语解释。
用户询问期权希腊字母(如delta, gamma, theta, vega) 需要计算隐含波动率(IV) 进行期权敏感性分析
.claude/skills/greeks/SKILL.md
npx skills add staskh/trading_skills --skill greeks -g -y
SKILL.md
Frontmatter
{
    "name": "greeks",
    "description": "Calculate option Greeks (delta, gamma, theta, vega) and implied volatility for specific options. Use when user asks about Greeks, delta, gamma, theta, vega, IV, or option sensitivity analysis.",
    "dependencies": [
        "trading-skills"
    ]
}

Option Greeks

Calculate Greeks for options using Black-Scholes model. Computes IV from market price via Newton-Raphson.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/greeks.py --spot SPOT --strike STRIKE --type call|put [--expiry YYYY-MM-DD | --dte DTE] [--price PRICE] [--date YYYY-MM-DD] [--vol VOL] [--rate RATE]

Arguments

  • --spot - Underlying spot price (required)
  • --strike - Option strike price (required)
  • --type - Option type: call or put (required)
  • --expiry - Expiration date YYYY-MM-DD (use this OR --dte)
  • --dte - Days to expiration (alternative to --expiry)
  • --date - Calculate as of this date instead of today (YYYY-MM-DD)
  • --price - Option market price (for IV calculation)
  • --vol - Override volatility as decimal (e.g., 0.30 for 30%)
  • --rate - Risk-free rate (default: 0.05)

Output

Returns JSON with:

  • spot - Underlying spot price
  • strike - Strike price
  • days_to_expiry - Days until expiration
  • iv - Implied volatility (calculated from market price)
  • greeks - delta, gamma, theta, vega, rho

Examples

# With expiry date and market price (calculates IV)
uv run python scripts/greeks.py --spot 630 --strike 600 --expiry 2026-05-15 --type call --price 72.64

# With DTE directly
uv run python scripts/greeks.py --spot 630 --strike 600 --dte 30 --type call --price 40

# As of a future date
uv run python scripts/greeks.py --spot 630 --strike 600 --expiry 2026-05-15 --date 2026-03-01 --type call --price 50

Explain what each Greek means for the position.

Dependencies

  • scipy

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
从 Interactive Brokers 获取账户摘要,包括现金余额、购买力和账户价值。当用户询问账户、余额或可用资金时触发。需本地运行 TWS 或 IB Gateway。
查询账户状态 查看现金余额 检查购买力 获取可用资金
.claude/skills/ib-account/SKILL.md
npx skills add staskh/trading_skills --skill ib-account -g -y
SKILL.md
Frontmatter
{
    "name": "ib-account",
    "description": "Get account summary from Interactive Brokers including cash balance, buying power, and account value. Use when user asks about their account, balance, buying power, or available cash. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Account

Fetch account summary from Interactive Brokers.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/account.py [--port PORT] [--account ACCOUNT_ID] [--all-accounts]

Arguments

  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific account ID to fetch
  • --all-accounts - Fetch summaries for all managed accounts

Default behavior (no flags): fetches the first managed account only. Always use --all-accounts unless the user asks for a specific account.

Output

Returns JSON with:

  • connected - Whether connection succeeded
  • accounts - List of account summaries, each with account ID, net liquidation, cash, buying power, etc.

If not connected, explain that TWS/Gateway needs to be running.

Dependencies

  • ib-async

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
为保护PMCC头寸,在财报或高风险事件前生成战术领口策略报告。需本地运行TWS/Gateway,自动检测端口,分析头寸健康度、期权成本及情景损益,输出Markdown报告并提供实施建议。
用户询问如何保护现有PMCC头寸 用户要求生成财报前的风险管理报告 用户请求分析特定股票的领口策略
.claude/skills/ib-collar/SKILL.md
npx skills add staskh/trading_skills --skill ib-collar -g -y
SKILL.md
Frontmatter
{
    "name": "ib-collar",
    "description": "Generate tactical collar strategy reports for protecting PMCC positions through earnings or high-risk events. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Tactical Collar

Generate a tactical collar strategy report for protecting PMCC positions through earnings or high-risk events.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Gather Data

uv run python scripts/collar.py SYMBOL [--port PORT] [--account ACCOUNT]

The script returns JSON to stdout with all position and scenario data.

Step 2: Format Report

Read templates/markdown-template.md for formatting instructions. Generate a markdown report from the JSON data and save to sandbox/.

Step 3: Report Results

Present key findings to the user: recommended put protection, cost/benefit, and the saved report path.

Arguments

  • SYMBOL - Stock symbol to analyze (must be in portfolio)
  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific account ID (optional, searches all accounts)

JSON Output

The script returns JSON with these key fields:

  • symbol, current_price - Basic info
  • long_strike, long_expiry, long_qty, long_cost - LEAPS position
  • short_positions - List of short calls
  • is_proper_pmcc, short_above_long - PMCC health flags
  • earnings_date, days_to_earnings - Earnings timing
  • put_analysis - List of put scenarios with costs and P&L under gap up/flat/down
  • unprotected_loss_10, unprotected_loss_15, unprotected_gain_10 - LEAPS risk without collar
  • volatility - Historical volatility data

Report Sections

  1. Position Summary: Current PMCC structure (long calls, short calls)
  2. PMCC Health Check: Is structure proper (short > long strike) or broken?
  3. Earnings Risk: Next earnings date and days until event
  4. Put Duration Analysis: Comparison of short vs medium vs long-dated puts
  5. Collar Scenarios: Gap up, flat, gap down outcomes with each put duration
  6. Cost/Benefit Analysis: Insurance cost vs protection value
  7. Implementation Timeline: Step-by-step checklist with dates
  8. Recommendation: Optimal put strike and expiration

Key Concepts

Proper PMCC Structure:

  • Long deep ITM LEAPS call
  • Short OTM calls ABOVE long strike
  • No additional margin required for collar

Broken PMCC Structure:

  • Long call is now OTM (after crash)
  • Short calls BELOW long strike require margin
  • Collar still works but margin implications exist

Tactical Collar:

  • Buy protective puts ONLY before high-risk events (earnings)
  • Sell puts after event passes
  • Balances income generation with crash protection

Put Duration Trade-offs:

  • Short-dated: Cheaper, more gamma, but zero salvage on gap up
  • Medium-dated (2-4 weeks): Best balance of cost, gamma, and salvage
  • Long-dated: Preserves value on gap up, but expensive and less gamma

Example Usage

# Analyze NVDA position (defaults to paper port 7497)
uv run python scripts/collar.py NVDA

# Analyze specific account
uv run python scripts/collar.py AMZN --account U790497

# Use paper trading port instead
uv run python scripts/collar.py NVDA --port 7497

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
用于整合IBKR交易CSV文件,按标的、日期等维度汇总数据并生成Markdown和CSV报告。支持自动探测端口获取未实现盈亏,强制使用纽约时区,输出包含生成时间及延迟字段。
需要合并多个IBKR交易CSV文件 生成期权或股票交易的汇总报表
.claude/skills/ib-create-consolidated-report/SKILL.md
npx skills add staskh/trading_skills --skill ib-create-consolidated-report -g -y
SKILL.md
Frontmatter
{
    "name": "ib-create-consolidated-report",
    "description": "Consolidate IBRK trade CSV files from a directory into a summary report. Groups trades by symbol, underlying, date, strike, buy\/sell, and open\/close. Outputs both markdown and CSV.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Create Consolidated Report

Reads all CSV files from a given directory (excluding subdirectories), consolidates trade data by key fields, and generates both markdown and CSV reports.

Instructions

uv run python scripts/consolidate.py <directory> [--port PORT] [--output-dir OUTPUT_DIR]

Arguments

  • directory - Path to directory containing IBRK trade CSV files
  • --port - IB port to fetch unrealized P&L (7497=paper, 7496=live). If not specified, auto-probes both ports (tries 7496 first, then 7497).
  • --output-dir - Output directory for reports (default: sandbox/)

Consolidation Logic

Groups trades by:

  • UnderlyingSymbol - The underlying ticker (e.g., GOOG, CAT)
  • Symbol - Full option symbol
  • TradeDate - Date of the trade
  • Strike - Strike price
  • Put/Call - Option type (C or P)
  • Buy/Sell - Trade direction
  • Open/CloseIndicator - Whether opening or closing

Aggregates:

  • Quantity - Sum of quantities
  • Proceeds - Sum of proceeds
  • NetCash - Sum of net cash
  • IBCommission - Sum of commissions
  • FifoPnlRealized - Sum of realized P&L

Adds column:

  • Position - SHORT (Sell+Open), LONG (Buy+Open), CLOSE_SHORT (Buy+Close), CLOSE_LONG (Sell+Close)

Output

Generates two files in the output directory:

  • consolidated_trades_YYYY-MM-DD_HHMM.md - Markdown report with summary tables
  • consolidated_trades_YYYY-MM-DD_HHMM.csv - CSV with all consolidated data

Example Usage

# Consolidate trades from IBRK reports directory
uv run python scripts/consolidate.py "C:\Users\avrah\OneDrive\Business\Trading\IBRK reports\2stastrading2025"

# Specify custom output directory
uv run python scripts/consolidate.py "C:\path\to\reports" --output-dir "C:\output"

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
基于IB实时数据,分析现有空头头寸的展期策略,或为多头股票/期权寻找最佳备兑开仓及价差构建方案。支持自动端口检测与账户记忆,生成Markdown报告展示推荐头寸、盈亏及关键指标。
用户询问如何滚动(roll)现有空头期权头寸 用户希望为持有的正股或期权寻找最佳的备兑看涨/看跌期权或价差策略
.claude/skills/ib-find-short-roll/SKILL.md
npx skills add staskh/trading_skills --skill ib-find-short-roll -g -y
SKILL.md
Frontmatter
{
    "name": "ib-find-short-roll",
    "description": "Find roll options for existing short positions OR find best covered call\/put to open against long stock. Use when user asks about rolling shorts, finding roll candidates, writing covered calls, or managing option positions. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Find Short Roll

Analyze roll options for short positions or find best short options to open against long stock using real-time data from Interactive Brokers.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Gather Data

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/roll.py SYMBOL [--strike STRIKE] [--expiry YYYYMMDD] [--right C|P] [--port PORT] [--account ACCOUNT] [--iv-multiplier N]

The script returns JSON to stdout with all position and candidate data.

Step 2: Format Report

Read templates/markdown-template.md for formatting instructions. Generate a markdown report from the JSON data and save to sandbox/.

Step 3: Report Results

Present key findings to the user: recommended position, credit/debit, and the saved report path.

Behavior

  1. If short option position exists (mode: "roll"): Analyzes roll candidates to different expirations/strikes
  2. If long option position exists (mode: "spread"): Finds best short call/put to create a vertical spread
  3. If long stock exists (mode: "new_short"): Finds best covered call (or protective put) to open
  4. If none of the above: Returns error (use --strike/--expiry to specify manually)

Arguments

  • SYMBOL - Ticker symbol (e.g., GOOG, AAPL, TSLA)
  • --strike - Current short strike price (optional, auto-detects from portfolio)
  • --expiry - Current short expiration in YYYYMMDD format (optional, auto-detects)
  • --right - Option type: C for call, P for put (default: C)
  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific account ID (optional)
  • --iv-multiplier - Expected-move multiplier for strike band width (default: 2.0); increase for high-IV names to surface wider roll candidates

JSON Output

The script outputs JSON with mode field indicating the analysis type:

Common Fields

  • success - Boolean
  • generated - Timestamp
  • mode - "roll", "spread", or "new_short"
  • symbol - Ticker
  • underlying_price - Current stock price
  • earnings_date - Next earnings date or null
  • expirations_analyzed - List of expiry dates checked

Mode-specific Fields

  • roll: current_position (includes iv and delta from IB greeks), buy_to_close, roll_candidates (dict of expiry -> candidates), iv_multiplier
  • spread: long_option, right, candidates_by_expiry
  • new_short: long_position, right, candidates_by_expiry, iv_multiplier

Strike Band Logic (roll and new_short modes)

The strike search window is IV-aware: half_band = iv_multiplier × ATM_IV × spot × √(T/365) where T is the DTE of the nearest roll expiry. For roll mode, ATM IV comes from IB model greeks on the current position's quote; if unavailable, it is estimated from the option mid-price using the Brenner-Subrahmanyam approximation. For new_short mode, a conservative default IV of 30% is used. This makes the band automatically wider for high-IV underlyings without requiring a manual override.

Example Usage

# Auto-detect GOOG position (short option, long option, or long stock)
uv run python scripts/roll.py GOOG --port 7497

# Specify exact short position to roll
uv run python scripts/roll.py GOOG --strike 350 --expiry 20260206 --right C

# Find short call to sell against long call (vertical spread)
uv run python scripts/roll.py AUR --right C

# Find covered put for long stock
uv run python scripts/roll.py TSLA --right P

Dependencies

  • ib-async
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
从Interactive Brokers获取股票、ETF及期货期权的完整链数据,包括买卖价、隐含波动率和希腊值。支持自动识别资产类型与端口回退,适用于需要IBKR实时期权报价的场景。
查询期权链数据 获取IBKR期权报价 分析期货期权(如NQ/ES)
.claude/skills/ib-option-chain/SKILL.md
npx skills add staskh/trading_skills --skill ib-option-chain -g -y
SKILL.md
Frontmatter
{
    "name": "ib-option-chain",
    "description": "Get option chain data from Interactive Brokers for equities, ETFs, and futures (FOP), including calls and puts with strikes, bids, asks, volume, implied volatility, and model Greeks. Use when user asks about options using IBKR data, futures options (NQ\/ES\/CL\/GC...), or needs real-time option quotes from their broker. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Option Chain

Fetch option chain data from Interactive Brokers for a specific expiration date. Handles equities/ETFs (Stock/OPT) and futures options (FOP). The asset type and exchange are resolved from IB contract details (no hardcoded symbol table): auto-detect tries a SMART stock first and falls back to a future when no stock exists (so NQ, GC, RTY resolve as futures, while AAPL resolves as a stock even though it has an obscure single-stock future). Tickers that are both a stock and a futures root (e.g. ES=Eversource, CL=Colgate) default to the equity — pass --sec-type fut to force the future.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

First, get available expiration dates:

uv run python scripts/options.py SYMBOL --expiries

Then fetch the chain for a specific expiry:

uv run python scripts/options.py SYMBOL --expiry YYYYMMDD

Arguments

  • SYMBOL - Ticker symbol. Equity/ETF (e.g., AAPL, SPY, TSLA) or futures root (e.g., NQ, ES, CL, GC) — asset type is auto-detected via IB.
  • --sec-type {stk,fut} - Force the asset type. Default: auto-detect (stock-first). Use fut for ambiguous roots like ES/CL when you mean the future.
  • --expiries - List available expiration dates only
  • --expiry YYYYMMDD - Fetch chain for specific date (IB format: YYYYMMDD, no dashes)
  • --port - IB port (default: 7497 for paper trading)

Output

Returns JSON with:

  • calls - Array of call options with strike, bid, ask, lastPrice, volume, openInterest, impliedVolatility, greeks (delta/gamma/theta/vega/iv from IB model), and multiplier (futures only)
  • puts - Array of put options with same fields
  • underlying_price - Current underlying price for reference (stock/ETF price or continuous-future price)
  • asset_type - "stock" or "future"
  • source - "ibkr"

For futures, only expiries up to the front continuous-future's expiry are returned; longer-dated FOPs require the next quarter's future. Futures quote nearly 24h on Globex, so Greeks populate pre-market.

Present data as a table. Highlight high volume strikes and notable IV levels.

Dependencies

  • ib-async

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
分析IB账户PMCC对角价差持仓,评估短腿风险、每日盈亏及推荐换仓。支持自动连接TWS/Gateway,默认输出简洁摘要,按需生成包含技术面、风险评估和对比表的Markdown报告或JSON数据文件。
查询PMCC持仓状态 分析短腿行权风险 获取每日盈亏预测 寻找换仓建议 生成详细分析报告
.claude/skills/ib-pmcc-advisor/SKILL.md
npx skills add staskh/trading_skills --skill ib-pmcc-advisor -g -y
SKILL.md
Frontmatter
{
    "name": "ib-pmcc-advisor",
    "description": "Analyze PMCC (Poor Man's Covered Call \/ diagonal spread) positions from IB portfolio. For each diagonal spread, reports short leg risk (delta, IV, assignment probability), daily P&L projections, top-3 roll candidates, and a side-by-side comparison table. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB PMCC Advisor

Analyzes all PMCC (diagonal call spread) positions in the IB portfolio and provides actionable advice on the short leg: assignment risk, P&L projections per day, and ranked roll recommendations.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Run the script

uv run python .claude/skills/ib-pmcc-advisor/scripts/pmcc_advisor.py [--port PORT] [--account ACCOUNT] [--min-roll-dte N] [--price-mode mid|last]

The script returns JSON to stdout. Parse it and use it for the response below.

Step 2: Default response — brief inline summary

Unless the user explicitly asks for a report or JSON output, respond with a concise inline summary only. No files saved.

Format:

  • One line per spread: SYMBOL — short $STRIKE exp DATE (δ=X, assign=Y%) — [HOLD / ROLL to $STRIKE]
  • Lead with any red flags (assignment > 40%, DTE < 7, earnings within short window).
  • For flagged spreads, add one extra line with the top roll candidate and net credit.
  • Clean positions: the one-line summary is enough.

Step 3: Generate files only when explicitly requested

MD report — triggered by: "save a report", "generate a report", "write a report", "markdown", "PDF".

Read .claude/skills/ib-pmcc-advisor/templates/markdown-template.md for full formatting instructions. Save to sandbox/pmcc_advisor_{ACCOUNT}_{YYYY-MM-DD}_{HHmm}.md. Use first account ID; derive timestamp from generated_at.

The report must include all sections per spread:

  1. Red flags summary — assignment > 40%, DTE < 7, no rolls, earnings warnings
  2. Company description — one sentence from your own knowledge (always)
  3. Technical profile — RSI, MACD, EMA crossover, ADX, SMA distance, 3mo return, bullish score (only if technical data is present in conversation context; omit otherwise)
  4. Spread structure table — both legs: strike, expiry, DTE, cost, current price, IV
  5. Short leg risk — delta (BS + IB), assignment probability with risk label
  6. Daily P&L projections — all rows: date, days to expiry, best exit spot, max P&L (mark peak row)
  7. Roll candidates table — strike, expiry, DTE, delta, assign%, IV, net credit, $/day, P&L if assigned, bid/ask
  8. Comparison table — current vs roll_1/2/3 side by side
  9. Recommendation — hold/roll/close with reasoning

JSON output — triggered by: "save JSON", "export JSON", "save the data", "output file".

Save raw script output to sandbox/pmcc_advisor_{ACCOUNT}_{YYYY-MM-DD}_{HHmm}.json.

Arguments

Flag Default Description
--port 7497 IB Gateway/TWS port
--account all Specific account ID
--min-roll-dte 7 Minimum DTE for roll candidates
--price-mode mid Option price: mid (bid+ask)/2 or last
--symbols all Analyze only these symbols (e.g. --symbols NVDA WMT)

JSON Output Structure

{
  "generated_at": "2026-04-30 10:25 ET",
  "data_delay": "real-time",
  "accounts": ["Uxxxxxxxx"],
  "price_mode": "mid",
  "min_roll_dte": 7,
  "symbols_filter": ["NVDA", "WMT"],
  "spreads": [
    {
      "symbol": "NVDA",
      "account": "Uxxxxxxxx",
      "qty": 10,
      "underlying_price": 201.46,
      "leaps_expiry": "20260918",
      "earnings": {
        "date": "2026-05-20",
        "timing": "AMC",
        "warning_short": false,
        "warning_roll_indices": [1, 2, 3]
      },
      "long": {
        "strike": 180.0, "expiry": "20260918", "dte": 141,
        "avg_cost": 35.51, "current_price": 36.20,
        "iv_pct": 42.1, "ib_delta": 0.7821, "ib_iv_pct": 41.8
      },
      "short": {
        "strike": 210.0, "expiry": "20260618", "dte": 49,
        "premium_received": 6.88, "current_price": 5.10,
        "iv_pct": 38.5, "delta": 0.3421, "assignment_prob_pct": 28.4,
        "ib_delta": 0.3415, "ib_iv_pct": 38.2
      },
      "daily_pnl": [
        {"date": "2026-04-30", "days_to_short_expiry": 49.0, "optimal_spot": 215.20, "pnl": 1234.56},
        {"date": "2026-05-01", "days_to_short_expiry": 48.0, "optimal_spot": 214.80, "pnl": 1289.10}
      ],
      "roll_candidates": [
        {
          "strike": 215.0, "expiry": "20260717", "dte": 78,
          "price": 5.80, "delta": 0.2910, "assignment_prob": 22.5,
          "iv_pct": 37.2, "net_credit": 0.70, "profit_per_day": 0.0744,
          "pnl_if_assigned": 3580.0, "bid": 5.60, "ask": 6.00
        }
      ],
      "comparison": {
        "current":  {"strike": 210, "expiry": "20260618", "dte": 49, "delta": 0.3421, "assignment_prob": 28.4, "profit_per_day": 0.1404, "pnl_if_assigned": 1880.0},
        "roll_1":   {"strike": 215, "expiry": "20260717", "dte": 78, "delta": 0.2910, "assignment_prob": 22.5, "profit_per_day": 0.0744, "pnl_if_assigned": 3580.0}
      }
    }
  ]
}

Key Fields

  • symbols_filter — list of uppercase symbols when --symbols was used; null means full portfolio
  • data_delay"real-time" if live quotes available, "stalled - using last price" if IBKR quotes unavailable
  • generated_at — NY timezone timestamp
  • leaps_expiry — expiry of the long leg (YYYYMMDD); all roll candidates are capped at or before this date
  • earnings.date — next earnings date (YYYY-MM-DD) from Yahoo Finance; null for ETFs
  • earnings.timing"BMO" (before open) or "AMC" (after close)
  • earnings.warning_short — true if earnings fall within the last 7 calendar days before short expiry
  • earnings.warning_roll_indices — 1-based indices of roll candidates whose expiry window contains the earnings date
  • delta / ib_delta — BS-calculated vs. IBKR model Greeks (both reported when available)
  • iv_pct / ib_iv_pct — IV in percent; BS-calculated from option price vs. IBKR model Greeks
  • assignment_prob_pct — N(d2): risk-neutral probability the short expires ITM
  • net_credit — credit received when rolling (negative = debit); rolls with debit > $0.10/share excluded
  • pnl_if_assigned — P&L if underlying finishes above short_strike at expiry: (short_strike - long_strike - long_cost + total_premium) × 100
  • daily_pnl[].optimal_spot — spot price that maximises exit P&L on that day (found via numerical optimisation); increases as theta decays the short leg
  • daily_pnl[].pnl — total dollars (qty × 100 contracts) at the optimal spot on that day

Roll Selection Criteria

Candidates must satisfy both:

  1. Delta ≤ 0.40 (absolute cap — allows same-strike forward rolls when current short is near expiry)
  2. Net credit ≥ -$0.10/share (not a large debit)

Scans the next 5 available chain expirations after the current short expiry, bounded by the LEAPS expiry.

Ranked by: delta improvement (highest weight) → net credit → DTE extension.

Example Usage

# All accounts (paper, default)
uv run python .claude/skills/ib-pmcc-advisor/scripts/pmcc_advisor.py

# Live account, 14-day minimum roll DTE, last-price mode
uv run python .claude/skills/ib-pmcc-advisor/scripts/pmcc_advisor.py --port 7496 --account Uxxxxxxxx --min-roll-dte 14 --price-mode last

# Analyze only specific symbols
uv run python .claude/skills/ib-pmcc-advisor/scripts/pmcc_advisor.py --symbols NVDA WMT

Architecture

All logic lives in src/trading_skills/broker/pmcc_advisor.py:

  • Analytics functions (top half, no IBKR imports): get_option_price, calc_iv, calc_delta, calc_assignment_prob, calc_bs_price, calc_daily_pnl_table, check_earnings_warning, find_best_rolls, build_comparison_table, score_roll_candidate
  • Data layer (bottom half, uses IBKR + Yahoo Finance): get_pmcc_data, _identify_pmcc_spreads, _fetch_single_option_quote, _fetch_option_quotes_batch, _get_chain_params, _fetch_earnings_dates

Reuses from src/trading_skills/broker/:

  • connection.pyib_connection, CLIENT_IDS, fetch_positions, fetch_spot_prices, normalize_positions, best_option_chain
  • black_scholes.pyimplied_volatility, black_scholes_price, black_scholes_delta, estimate_iv
Dependencies: trading-skills
生成涵盖IB账户持仓、收益日期及风险评估的综合行动报告。需本地运行TWS/Gateway,自动处理端口回退,输出带红绿灯风险指示的Markdown报告,提示紧急操作项。
用户请求投资组合审查 查询行动事项 评估收益风险 管理IB账户持仓
.claude/skills/ib-portfolio-action-report/SKILL.md
npx skills add staskh/trading_skills --skill ib-portfolio-action-report -g -y
SKILL.md
Frontmatter
{
    "name": "ib-portfolio-action-report",
    "description": "Generate a comprehensive portfolio action report with earnings dates and risk assessment. Use when user asks for portfolio review, action items, earnings risk, or position management across IB accounts. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Portfolio Action Report

Generate a comprehensive portfolio action report that analyzes all positions across Interactive Brokers accounts, fetches earnings dates, and provides traffic-light risk indicators (🔴🟡🟢) for each position.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Gather Data

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/report.py [--port PORT] [--account ACCOUNT]

The script returns JSON to stdout with analyzed portfolio data including risk levels, earnings dates, technical indicators, and spread groupings.

Step 2: Format Report

Read templates/markdown-template.md for formatting instructions. Generate a markdown report from the JSON data and save to sandbox/.

Filename: ib_portfolio_action_report_{ACCOUNT}_{YYYY-MM-DD}_{HHmm}.md

Step 3: Report Results

Present critical findings to the user: red/yellow items requiring attention, top priority actions, and the saved report path.

Arguments

  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific account ID to analyze (optional, defaults to all accounts)

JSON Output

The script returns structured JSON with:

  • generated_at - NY timestamp (e.g. "2026-04-29 19:35 ET")
  • data_delay - Data freshness ("real-time")
  • accounts - List of account IDs
  • summary - Red/yellow/green counts
  • spreads - All positions grouped into spreads with risk level, urgency, and recommendations
  • technicals - Technical indicators per symbol (RSI, trend, SMAs, MACD, ADX)
  • earnings - Earnings dates per symbol
  • prices - Current prices per symbol
  • earnings_calendar - Upcoming earnings with account/position info
  • account_summary - Position and risk counts per account

Report Sections

  1. Critical Summary: Count of positions by risk level (🔴/🟡/🟢)
  2. Immediate Action Required: Positions expiring within 2 days
  3. Urgent - Expiring Within 1 Week: Short-term positions needing attention
  4. Critical Earnings Alert: Positions with earnings this week
  5. Earnings Next Week: Upcoming earnings exposure
  6. Expiring in 2 Weeks: Medium-term expirations
  7. Longer-Dated Positions: Core holdings with spread analysis
  8. Top Priority Actions: Numbered action items by urgency
  9. Position Size Summary: Account-level breakdown
  10. Earnings Calendar: Next 30 days of earnings dates
  11. Technical Analysis Summary: RSI, trend, SMAs, MACD, ADX for each underlying

Example Usage

# All accounts (paper, default)
uv run python scripts/report.py

# Live account
uv run python scripts/report.py --port 7496

# Specific account
uv run python scripts/report.py --account U790497

Dependencies

  • ib-async
  • pandas-ta
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
从 Interactive Brokers 获取投资组合持仓信息。当用户询问持仓、头寸或持有股票时使用。需本地运行 TWS 或 IB Gateway,支持自动端口回退及纽约时区输出。
查询投资组合 查看持仓情况 询问持有的股票
.claude/skills/ib-portfolio/SKILL.md
npx skills add staskh/trading_skills --skill ib-portfolio -g -y
SKILL.md
Frontmatter
{
    "name": "ib-portfolio",
    "description": "Get portfolio positions from Interactive Brokers. Use when user asks about their portfolio, positions, holdings, or what stocks they own. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Portfolio

Fetch current portfolio positions from Interactive Brokers.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/portfolio.py [--port PORT]

Arguments

  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific IB account ID (optional, defaults to first account)

Output

Returns JSON with:

  • connected - Whether connection succeeded
  • positions - Array of positions with symbol, quantity, avg_cost, market_value, unrealized_pnl

If not connected, explain that TWS/Gateway needs to be running.

Dependencies

  • ib-async

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
计算并报告所有IBKR账户的Delta调整名义敞口。基于Black-Scholes模型计算期权Delta,按账户和标的资产报告多空敞口及风险概况,适用于询问Delta敞口或投资组合方向性风险时。
用户询问Delta敞口 用户询问投资组合风险 用户询问方向性敞口
.claude/skills/ib-report-delta-adjusted-notional-exposure/SKILL.md
npx skills add staskh/trading_skills --skill ib-report-delta-adjusted-notional-exposure -g -y
SKILL.md
Frontmatter
{
    "name": "ib-report-delta-adjusted-notional-exposure",
    "description": "Report delta-adjusted notional exposure across all IBKR accounts. Calculates option deltas using Black-Scholes and reports long\/short exposure by account and underlying. Use when user asks about delta exposure, portfolio risk, or directional exposure.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Delta-Adjusted Notional Exposure Report

Calculate and report delta-adjusted notional exposure across all Interactive Brokers accounts.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Gather Data

uv run python scripts/delta_exposure.py [--port PORT]

The script returns JSON to stdout with all position deltas and summary data.

Step 2: Format Report

Read templates/markdown-template.md for formatting instructions. Generate a markdown report from the JSON data and save to sandbox/.

Filename: delta_exposure_report_{YYYYMMDD}_{HHMMSS}.md

Step 3: Report Results

Present the summary table (total long, short, net) and top exposures to the user. Include the saved report path.

Arguments

  • --port - IB port (default: 7497 for paper trading)

JSON Output

Returns delta-adjusted notional exposure with:

  • connected - Boolean
  • accounts - List of account IDs
  • position_count - Total positions
  • positions - Array of positions with symbol, delta, delta_notional, spot price
  • summary - Totals for long, short, and net delta notional
    • by_account - Long/short breakdown by account
    • by_underlying - Long/short/net breakdown by symbol

Methodology

  • Equity Options: Delta calculated via Black-Scholes with estimated IV based on moneyness
  • Futures: Delta = 1.0 (full notional exposure)
  • Futures Options: Delta calculated with lower IV assumption (20%)
  • Stocks: Delta = 1.0

Delta-adjusted notional = delta x spot price x quantity x multiplier

Examples

# Paper trading (default)
uv run python scripts/delta_exposure.py

# Live trading
uv run python scripts/delta_exposure.py --port 7496

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
IB止损管理器,分析PMCC、裸LEAPS和股票持仓。计算止损价、检测警报并放置条件组合订单。默认干跑模式,需本地运行TWS或IB Gateway。支持自动端口回退及强制执行。
用户请求检查投资组合的止损状态 用户要求执行或模拟交易止损策略 需要查看期权或股票的预警信号
.claude/skills/ib-stop-loss/SKILL.md
npx skills add staskh/trading_skills --skill ib-stop-loss -g -y
SKILL.md
Frontmatter
{
    "name": "ib-stop-loss",
    "description": "Downside stop-loss management for PMCC, naked LEAPS, and stock positions in IB. Computes stop prices, detects alerts, and places conditional combo orders. Dry-run by default. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Stop-Loss Manager

Analyzes PMCC (diagonal call spread), naked LEAPS, and stock positions in the IB portfolio and manages conditional stop-loss orders.

Default mode is dry-run — no orders are placed unless --execute is in the request.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Run the script

Dry-run (default — no orders placed):

uv run python .claude/skills/ib-stop-loss/scripts/stop_loss.py

Execute (cancel orphan orders + place SL_ conditional orders):

uv run python .claude/skills/ib-stop-loss/scripts/stop_loss.py --execute

Execute forced (basis = current mid price, can lower existing stops):

uv run python .claude/skills/ib-stop-loss/scripts/stop_loss.py --execute --forced

Step 2: Format the report

Format JSON output as a markdown report with four sections:

Section 1: Alert Soon

List symbols in alert_soon prominently — these are past the early-warning threshold.

Section 2: Existing Conditional Orders

Show all_conditional_orders.module (SL_ orders) and all_conditional_orders.manual (manually placed). If orphan_orders is non-empty, warn that these were cancelled (execute mode) or need manual cancellation (dry-run).

Section 3: Positions

For each entry in positions, show a table:

Field Value
Symbol NVDA — pmcc (3 contracts)
Spot $219.05
LEAPS 200C 20270115 · avg cost $44.27 · current $44.23 · basis $44.27
Stop price $22.14 (40% stop) → action: place_new
LEAPS loss 0.1%
Shorts 235C 20260515 · received $0.61 · current $0.56 · 9.5% decayed

Show preserve_existing when a more-protective stop already exists. Show overwrite (red) when forced=true lowers an existing stop.

Section 4: Alerts

Group alerts by symbol. Types:

Type Meaning
leaps_early_warning LEAPS down ≥ stop_pct/2% from basis
short_premium_decay 90%+ of short premium captured — close or roll
short_near_strike Spot at/above or within X% of short strike

Step 3: Report to user

  • State dry-run vs execute mode prominently.
  • Lead with alert_soon symbols.
  • For each position: show stop action and current loss %.
  • Show alerts section last.

Arguments

Flag Default Description
--port 7497 IB Gateway/TWS port
--account all Specific account ID
--symbols all Analyze only these symbols
--legs none Specific option legs: SYMBOL:STRIKE[C|P]:EXPIRY (e.g. IBKR:70C:20270115 IBKR:100C:20260918). Right defaults to C. Takes precedence over --symbols. Use when multiple PMCC/LEAPS coexist on the same symbol and only one pairing should get a stop.
--stop-pct 40 Loss % that triggers exit
--short-near-strike-pct 5 Near-strike alert threshold
--price-mode mid Option pricing: mid or last
--execute off Cancel orphans + place SL_ orders
--forced off Use current mid as basis (requires --execute)

JSON Output Structure

{
  "generated_at": "2026-05-12 10:00 ET",
  "dry_run": true,
  "forced": false,
  "stop_pct": 40.0,
  "short_near_strike_pct": 5.0,
  "accounts": ["U1234567"],
  "symbols_filter": null,
  "all_conditional_orders": {"module": [], "manual": []},
  "orphan_orders": [],
  "alert_soon": ["PFE"],
  "positions": [
    {
      "symbol": "NVDA",
      "type": "pmcc",
      "account": "U1234567",
      "qty": 3,
      "underlying_price": 219.05,
      "leaps": {
        "strike": 200.0, "expiry": "20270115", "avg_cost": 44.27,
        "current_price": 44.23, "stop_basis": 44.27,
        "stop_price": 22.14, "loss_pct": 0.1
      },
      "shorts": [
        {"strike": 235.0, "expiry": "20260515",
         "premium_received": 0.61, "current_price": 0.56, "decay_pct": 9.5}
      ],
      "stop_loss": {"stop_price": 22.14, "action": "place_new", "existing_stop": null},
      "alert_soon": false,
      "alerts": []
    },
    {
      "symbol": "AAPL",
      "type": "stock",
      "account": "U1234567",
      "qty": 100,
      "underlying_price": 189.50,
      "stock": {
        "avg_cost": 175.00, "stop_basis": 189.50,
        "stop_price": 94.75, "loss_pct": 0.0
      },
      "stop_loss": {"stop_price": 94.75, "action": "place_new", "existing_stop": null},
      "alert_soon": false,
      "alerts": []
    }
  ]
}

Key Fields

  • alert_soon — top-level list of symbols where loss ≥ stop_pct/2%
  • position.typepmcc | leaps | stock
  • stop_loss.actionplace_new | preserve_existing | overwrite
  • stop_loss.existing_stop — price of the existing SL_FALL_ order if present
  • For PMCC: stop order is a single combo (BAG) order closing LEAPS + all shorts atomically
  • In execute mode: orphan SL_ orders (no matching position) are cancelled first

Order Identification

  • SL_FALL_{SYM}_{STRIKE}_{EXPIRY} — options (PMCC or naked LEAPS)
  • SL_FALL_{SYM}_STK — stock positions

Architecture

All analytics live in src/trading_skills/broker/stop_loss.py:

Analytics (no IBKR — testable in isolation):

  • calc_stop_basis — max(mid, avg_cost) normally; current_mid if forced
  • calc_stop_price — basis × (1 - stop_pct/100)
  • calc_short_premium_decay_pct — % of short premium captured
  • identify_positions — classify normalized positions into pmcc/leaps/stock
  • build_position_analysis — full per-position output dict
  • detect_orphan_orders — SL_FALL_ orders for gone positions
  • summarize_all_conditional_orders — splits IB orders into module vs manual

Data layer (IBKR):

  • get_stop_loss_data — main entry point
  • _cancel_orphan_orders — cancel stale SL_ orders
  • _place_combo_stop_order — BAG order for PMCC (atomic LEAPS + shorts)
  • _place_simple_stop_order — single order for naked LEAPS or stock
  • _execute_position_stop — dispatch per position type
Dependencies: trading-skills
用于从 Interactive Brokers 获取交易执行记录。支持通过 API 查询近期(约7天)数据,或通过 FlexReport 获取完整历史。具备自动端口回退机制,可按账户、日期范围或代码筛选,支持合并多个查询或本地 XML 文件。
用户询问交易历史 用户查询特定股票的交易记录 用户需要导出或分析过往交易明细
.claude/skills/ib-trades-history/SKILL.md
npx skills add staskh/trading_skills --skill ib-trades-history -g -y
SKILL.md
Frontmatter
{
    "name": "ib-trades-history",
    "description": "Fetch trade executions from Interactive Brokers filtered by account, date range, or symbol. Supports live API (~7 days history) and FlexReport (full history). Use when user asks about their trades, executions, or transaction history. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Trades History

Fetch trade executions from Interactive Brokers.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

For full trade history beyond ~7 days, the user needs a Flex Web Service token and a pre-configured Trade query in IBKR Account Management.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

# Recent trades (last ~7 days via API)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts

# Filter by symbol
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --symbol AAPL

# Full history via FlexReport
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token YOUR_TOKEN --flex-query-id YOUR_QUERY_ID

# Custom date range (FlexReport)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token TOKEN --flex-query-id QID --start-date 2025-01-01 --end-date 2025-12-31

# Multiple queries (e.g., one per year to exceed 365-day limit)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token TOKEN --flex-query-id QID_2025 --flex-query-id QID_2026 --start-date 2025-01-01 --end-date 2026-12-31

# From local FlexReport XML files (no TWS/Gateway needed)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --file trades_2024.xml --file trades_2025.xml --symbol TSLA

# Mix files with date filtering
uv run python .claude/skills/ib-trades-history/scripts/trades.py --file exports/2025.xml --start-date 2025-06-01 --end-date 2025-12-31

Arguments

  • --port - IB port (default: 7497 for paper trading)
  • --account - Specific account ID to filter
  • --all-accounts - Fetch trades for all managed accounts
  • --symbol - Filter trades by symbol (e.g., AAPL)
  • --start-date - Start date in YYYY-MM-DD format (default: Jan 1 of current year)
  • --end-date - End date in YYYY-MM-DD format (default: today)
  • --flex-token - FlexReport token (enables extended history)
  • --flex-query-id - FlexReport query ID (repeatable — pass multiple to merge queries spanning different periods)
  • --file - Local FlexReport XML file path (repeatable — pass multiple to merge files). No TWS/Gateway needed

Default behavior (no flags): fetches trades for the first managed account from the live API (~7 days). Always use --all-accounts unless the user asks for a specific account.

Data Sources

Scenario Source Date Range
No flex args reqExecutionsAsync ~last 7 days
--flex-token + --flex-query-id FlexReport (web) As configured in query
--file file (local XML) Full file contents

When using the live API, a data_limitation warning is included in the output.

Output

Returns JSON with:

  • connected - Whether connection succeeded
  • source - Data source used (reqExecutionsAsync or FlexReport)
  • filters - Applied filters (dates, symbol, account)
  • data_limitation - Warning about API date limits (only when using live API)
  • execution_count - Total number of executions returned
  • executions - List of individual trade executions
  • summary - Aggregated stats per symbol (bought, sold, commission, realized P&L)

If not connected, explain that TWS/Gateway needs to be running.

Dependencies

  • ib-async
Dependencies: trading-skills
管理IB股票和裸LEAPS的追踪止损。支持干跑与执行模式,自动处理端口回退及订单状态同步,排除PMCC头寸,生成包含持仓、现有订单及执行结果的详细报告。
用户请求为股票或LEAPS设置追踪止损 用户要求检查或更新现有的追踪止损订单 需要批量管理投资组合中的TRAIL订单
.claude/skills/ib-trailing-stop/SKILL.md
npx skills add staskh/trading_skills --skill ib-trailing-stop -g -y
SKILL.md
Frontmatter
{
    "name": "ib-trailing-stop",
    "description": "Server-side trailing stop management for stocks and naked LEAPS in IB. Places native TRAIL orders that auto-ratchet the stop as price climbs. Dry-run by default. Requires TWS or IB Gateway running locally.",
    "dependencies": [
        "trading-skills"
    ]
}

IB Trailing Stop Manager

Places IB native TRAIL orders against stocks and naked LEAPS in the portfolio. IB auto-adjusts the stop trigger as the price climbs and locks it as price falls.

PMCC positions are intentionally excluded — use ib-stop-loss for those (a standalone trailing stop on the PMCC long leg would break the hedge at trigger).

Default mode is dry-run — no orders are placed unless --execute is in the request.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Run the script

Dry-run (default — no orders placed):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --symbols JOBY --trail-pct 20

Execute (cancel orphan TS_ orders + place new TS_ TRAIL orders):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --symbols JOBY --trail-pct 20 --execute

Execute forced (cancel + replace existing TS_ orders with current parameters):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --execute --forced

Step 2: Format the report

Format JSON output as a markdown report with three sections:

Section 1: Existing TRAIL Orders

Show all_trail_orders.module (TS_ orders) and all_trail_orders.manual (manually placed). If orphan_orders is non-empty, warn that these were cancelled (execute mode) or need manual cancellation (dry-run).

Section 2: Positions

For each entry in positions, show a table:

Field Value
Symbol JOBY — stock (1000 shares)
Spot $7.50
Reference $7.50 (max of current $7.50, avg cost $5.00)
Trail params 20% (initial stop $6.00) → action: place_new
Existing trail none

For LEAPS rows, also show the option leg (strike/expiry) and current option mark.

action values:

  • place_new — no existing TS_ order; one will be created in execute mode
  • preserve_existing — TS_ already in place; left alone (IB has been tracking the high)
  • overwrite--forced is on; existing TS_ will be cancelled and replaced

Section 3: Order Results (execute mode only)

Per-position result with order_id and order_ref.

Step 3: Report to user

  • State dry-run vs execute mode prominently.
  • Lead with positions that have action: place_new (these are about to get a new TRAIL).
  • Call out preserve_existing separately so user knows nothing changed.
  • Show existing trail details (current trail_stop_price) so user knows where IB has trailed to.

Arguments

Flag Default Description
--port 7497 IB Gateway/TWS port
--account all Specific account ID
--symbols all Analyze only these symbols
--trail-pct 20 Trail amount as percentage of reference
--trail-amt Trail amount in dollars (mutually exclusive with --trail-pct)
--price-mode mid Option pricing: mid or last (LEAPS only)
--execute off Cancel orphans + place TS_ TRAIL orders
--forced off Cancel and replace existing TS_ orders (requires --execute)

JSON Output Structure

{
  "generated_at": "2026-05-29 10:00 ET",
  "data_delay": "real-time",
  "dry_run": true,
  "forced": false,
  "trail_pct": 20.0,
  "trail_amt": null,
  "accounts": ["U1234567"],
  "symbols_filter": ["JOBY"],
  "all_trail_orders": {"module": [], "manual": []},
  "orphan_orders": [],
  "positions": [
    {
      "symbol": "JOBY",
      "type": "stock",
      "account": "U1234567",
      "qty": 1000,
      "underlying_price": 7.50,
      "stock": {
        "avg_cost": 5.00,
        "current_price": 7.50
      },
      "trail_stop": {
        "trail_pct": 20.0,
        "trail_amt": null,
        "reference": 7.50,
        "initial_stop_price": 6.00,
        "action": "place_new",
        "existing_trail": null
      }
    }
  ]
}

Key Behaviors

  • Reference price = max(current_price, avg_cost) — locks in profit when above cost, never starts below entry.
  • Forced mode uses current_price as the reference (can place an initial stop below entry, useful when re-arming after a drawdown).
  • Existing TS_ orders are preserved by default because IB has been ratcheting the trail since placement — replacing would reset that tracked high. Use --forced to deliberately reset.
  • Scope: stocks + naked LEAPS only. PMCC positions are excluded; use ib-stop-loss for those.

Order Identification

  • TS_{SYM}_{STRIKE}_{EXPIRY}_{RIGHT} — naked LEAPS TRAIL orders (right is C or P so calls and puts on the same strike/expiry don't collide)
  • TS_{SYM}_STK — stock TRAIL orders

Architecture

All analytics live in src/trading_skills/broker/trailing_stop.py:

Analytics (no IBKR — testable in isolation):

  • calc_trail_referencemax(current_price, avg_cost) normally; current_price if forced
  • calc_initial_trail_stop_price — reference × (1 − trail_pct/100) or reference − trail_amt
  • identify_trailable_positions — stocks + naked LEAPS; PMCC excluded
  • build_trail_analysis — full per-position output dict
  • detect_orphan_trail_orders — TS_ TRAIL orders for gone positions
  • summarize_all_trail_orders — splits IB TRAIL orders into module vs manual

Data layer (IBKR):

  • get_trailing_stop_data — main entry point
  • _cancel_orphan_orders — cancel stale TS_ orders
  • _place_simple_trail_order — native TRAIL order on stock or option
  • _execute_position_trail — dispatch per position type
Dependencies: trading-skills
获取一只或多只股票的SEC Form 4内部人交易活动。支持查询高管买卖、交易详情及情绪分析,默认回溯90天,结果按净买入值排序。
查询内部人买入或卖出行为 查看高管交易记录 评估内部人市场情绪 搜索Form 4申报数据
.claude/skills/insider-trading/SKILL.md
npx skills add staskh/trading_skills --skill insider-trading -g -y
SKILL.md
Frontmatter
{
    "name": "insider-trading",
    "description": "Get insider trading activity (SEC Form 4 filings) for one or more stocks. Use when user asks about insider buying\/selling, executive transactions, insider sentiment, or Form 4 activity.",
    "dependencies": [
        "trading-skills"
    ]
}

Insider Trading

Fetch recent insider transactions from Yahoo Finance (SEC Form 4 data).

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/insider_trading.py SYMBOLS [--days DAYS]

Arguments

  • SYMBOLS - Single ticker or comma-separated list (e.g., NVDA or NVDA,PLTR,GOOG)
  • --days - Trailing days to look back (default: 90)

Output

Returns JSON with:

  • transactions - List of insider trades with insider name, role, transaction type, shares, price, value, date, ownership type
  • summary - Net sentiment (net_buying, net_selling, neutral), buy/sell counts and values

For multiple symbols, results are ranked by net buying value (most buying first).

Use Cases

  • "Show me insider buys for NVDA in the last 90 days"
  • "Compare insider activity across NVDA, PLTR, GOOG"
  • "Which of these stocks has the most insider selling recently?"

Dependencies

  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
将Markdown文件转换为专业格式PDF的Python工具。支持标题、表格、代码块等语法,无需系统依赖。
用户请求将.md文件转为PDF 其他技能需要生成Markdown内容的PDF
.claude/skills/markdown-to-pdf/SKILL.md
npx skills add staskh/trading_skills --skill markdown-to-pdf -g -y
SKILL.md
Frontmatter
{
    "name": "markdown-to-pdf",
    "arguments": [
        {
            "name": "file",
            "required": true,
            "description": "Path to the input markdown file"
        },
        {
            "name": "output",
            "required": false,
            "description": "Output PDF path. Defaults to same directory and basename as the input file."
        }
    ],
    "description": "Convert a markdown file to PDF using mistune + reportlab. Use when the user wants to convert a .md file to PDF, or when another skill needs to produce a PDF from markdown output.",
    "dependencies": [
        "trading-skills"
    ],
    "user_invocable": true
}

Markdown to PDF Converter

Converts a markdown file to a professionally formatted PDF. Pure Python — no system tools required.

Dependencies

Requires two Python packages (already in pyproject.toml):

mistune>=3.2
reportlab>=4.0

Install with: uv sync (or pip install mistune reportlab)

Instructions

uv run python .claude/skills/markdown-to-pdf/scripts/markdown_to_pdf.py <input.md> [output.pdf]
  • input.md — path to the markdown file (required)
  • output.pdf — output path (optional; defaults to same directory and basename as input)

Output

The script returns JSON with:

  • successtrue or false
  • input — resolved absolute path of the input file
  • output — resolved absolute path of the generated PDF
  • error — error message if success is false
  • generated_at — NY timezone timestamp
  • data_delay — always "real-time"

After conversion, tell the user the output PDF path.

Examples

# Convert sandbox/report.md → sandbox/report.pdf (default output)
uv run python .claude/skills/markdown-to-pdf/scripts/markdown_to_pdf.py sandbox/report.md

# Explicit output path
uv run python .claude/skills/markdown-to-pdf/scripts/markdown_to_pdf.py sandbox/report.md sandbox/AAPL_Report_2026-05-20_1430.pdf

Supported Markdown

  • Headings (H1–H3)
  • Paragraphs, bold, italic
  • Tables (pipe syntax)
  • Fenced code blocks
  • Unordered and ordered lists
Dependencies: trading-skills
获取股票的最新新闻及情绪分析。适用于用户询问特定股票的新闻动态、头条、市场情绪或近期重大事件时,调用脚本返回新闻列表及整体情绪摘要。
查询股票新闻 了解股票情绪 查看股票最新动态 询问某只股票发生了什么
.claude/skills/news-sentiment/SKILL.md
npx skills add staskh/trading_skills --skill news-sentiment -g -y
SKILL.md
Frontmatter
{
    "name": "news-sentiment",
    "description": "Get recent news and sentiment for a stock. Use when user asks about news, headlines, sentiment, what's happening with a stock, or recent developments.",
    "dependencies": [
        "trading-skills"
    ]
}

News Sentiment

Fetch recent news from Yahoo Finance.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/news.py SYMBOL [--limit LIMIT]

Arguments

  • SYMBOL - Ticker symbol
  • --limit - Number of articles (default: 10)

Output

Returns JSON with:

  • articles - Array of recent news with title, publisher, date, link
  • summary - Brief summary of overall sentiment

Present key headlines and note any significant news that could impact the stock.

Dependencies

  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
获取特定到期日的期权链数据,包括看涨/看跌期权、行权价、买卖价、成交量及隐含波动率。支持查询可用日期或指定日期,输出JSON并以表格展示,高亮关键指标。
用户询问期权价格 用户请求查看期权链 用户咨询看涨或看跌期权数据
.claude/skills/option-chain/SKILL.md
npx skills add staskh/trading_skills --skill option-chain -g -y
SKILL.md
Frontmatter
{
    "name": "option-chain",
    "description": "Get option chain data including calls and puts with strikes, bids, asks, volume, open interest, and implied volatility. Use when user asks about options, option prices, calls, puts, or option chain for a specific expiration date.",
    "dependencies": [
        "trading-skills"
    ]
}

Option Chain

Fetch option chain data from Yahoo Finance for a specific expiration date.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

First, get available expiration dates:

uv run python scripts/options.py SYMBOL --expiries

Then fetch the chain for a specific expiry:

uv run python scripts/options.py SYMBOL --expiry YYYY-MM-DD

Arguments

  • SYMBOL - Ticker symbol (e.g., AAPL, SPY, TSLA)
  • --expiries - List available expiration dates only
  • --expiry YYYY-MM-DD - Fetch chain for specific date

Output

Returns JSON with:

  • calls - Array of call options with strike, bid, ask, volume, openInterest, impliedVolatility
  • puts - Array of put options with same fields
  • underlying_price - Current stock price for reference

Present data as a table. Highlight high volume/OI strikes and notable IV levels.

Dependencies

  • pandas
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
获取股票历史OHLCV数据,支持按周期和间隔查询。适用于股价历史、过往表现、时间序列及图表分析场景。
用户询问股票价格历史 用户需要历史数据或过往表现分析 用户请求查看价格随时间的变化趋势 用户进行图表分析
.claude/skills/price-history/SKILL.md
npx skills add staskh/trading_skills --skill price-history -g -y
SKILL.md
Frontmatter
{
    "name": "price-history",
    "description": "Get historical price data (OHLCV) for a stock. Use when user asks about price history, historical data, past performance, price over time, or needs data for chart analysis.",
    "dependencies": [
        "trading-skills"
    ]
}

Price History

Fetch historical OHLCV data from Yahoo Finance.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/history.py SYMBOL [--period PERIOD] [--interval INTERVAL]

Arguments

  • SYMBOL - Ticker symbol
  • --period - Time period: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max (default: 1mo)
  • --interval - Data interval: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo (default: 1d)

Output

Returns JSON with:

  • symbol - Ticker
  • period - Requested period
  • interval - Data interval
  • data - Array of {date, open, high, low, close, volume}

Summarize key price movements, highs/lows, and trends.

Dependencies

  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
生成包含趋势、PMCC及基本面的专业股票分析报告。支持PDF和Markdown格式,整合多头扫描、财务指标、Piotroski评分及期权策略数据,输出推荐意见与详细分析。
用户请求生成股票分析报告 需要评估特定股票代码的投资价值 要求获取包含技术面和基本面的综合研报
.claude/skills/report-stock/SKILL.md
npx skills add staskh/trading_skills --skill report-stock -g -y
SKILL.md
Frontmatter
{
    "name": "report-stock",
    "arguments": [
        {
            "name": "symbols",
            "required": true,
            "description": "Stock ticker symbol(s) - single or space-separated list (e.g., AAPL or \"AAPL MSFT GOOGL\")"
        }
    ],
    "description": "Generate comprehensive stock analysis report (PDF or markdown) with trend, PMCC, and fundamental analysis",
    "dependencies": [
        "trading-skills"
    ],
    "user_invocable": true
}

Stock Analysis Report Generator

Generates professional reports with comprehensive stock analysis including trend analysis, PMCC viability, and fundamental metrics. Supports both PDF and markdown output formats.

Instructions

Step 1: Gather Data

Run the report script for each symbol:

uv run python scripts/report.py SYMBOL

The script returns detailed JSON with:

  • recommendation - Overall recommendation with strengths/risks
  • company - Company info (name, sector, industry, market cap)
  • trend_analysis - Bullish scanner results (score, RSI, MACD, ADX, SMAs)
  • pmcc_analysis - PMCC viability (score, LEAPS/short details, metrics)
  • fundamentals - Valuation, profitability, dividend, balance sheet, earnings history
  • piotroski - F-Score breakdown with all 9 criteria
  • spread_strategies - Option spread analysis (vertical spreads, straddle, strangle, iron condor)

Step 2: Generate Report

Step 2a — Write markdown

Read templates/markdown-template.md for formatting instructions. Generate a markdown report from the JSON data and save to sandbox/ as:

sandbox/{SYMBOL}_Analysis_Report_{YYYY-MM-DD}_{HHmm}.md

Step 2b — Convert to PDF (if requested)

Invoke the markdown-to-pdf skill on the markdown file just created:

uv run python .claude/skills/markdown-to-pdf/scripts/markdown_to_pdf.py sandbox/{SYMBOL}_Analysis_Report_{YYYY-MM-DD}_{HHmm}.md

The PDF is written alongside the markdown file with the same basename.

Step 3: Report Results

After generating the report, tell the user:

  1. The recommendation (BUY/HOLD/AVOID)
  2. Key strengths and risks
  3. The report file path

Example

# Single symbol
uv run python scripts/report.py AAPL

# Multiple symbols - run separately
uv run python scripts/report.py AAPL
uv run python scripts/report.py MSFT

Report Contents

All sections defined in templates/markdown-template.md:

  1. Header — symbol, company name, generated timestamp
  2. Recommendation — BUY/HOLD/AVOID with strengths and risks
  3. Company Overview — sector, industry, market cap, beta
  4. Trend Analysis — bullish score, RSI, MACD, ADX, SMA distances, earnings date, signals list
  5. Fundamental Analysis — valuation (P/E, P/B, EPS), profitability (margins, ROE, ROA, growth), dividend & balance sheet, earnings history (up to 8 quarters)
  6. Piotroski F-Score — all 9 criteria with PASS/FAIL
  7. Insider Trading — net sentiment, buy/sell counts, recent transactions (omitted if no data)
  8. PMCC Viability — score, IV, LEAPS/short leg details, trade metrics (yield, capital required)
  9. Option Spread Strategies — bull call, bear put, straddle, strangle, iron condor
  10. Investment Summary — strengths and risk factors
  11. Disclaimer footer

Dependencies

This skill aggregates data from:

  • scanner-bullish for trend analysis
  • scanner-pmcc for PMCC viability
  • fundamentals for financial data and Piotroski score

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
评估股票或头寸的风险指标,包括波动率、贝塔系数、VaR和回撤分析。适用于用户询问风险、波动性、价值风险或头寸规模等场景。
查询股票风险指标 计算波动率和贝塔值 评估VaR(价值风险) 分析最大回撤 确定头寸规模
.claude/skills/risk-assessment/SKILL.md
npx skills add staskh/trading_skills --skill risk-assessment -g -y
SKILL.md
Frontmatter
{
    "name": "risk-assessment",
    "description": "Assess risk metrics for a stock or position including volatility, beta, VaR, and drawdown analysis. Use when user asks about risk, volatility, beta, VaR, value at risk, drawdown, or position sizing.",
    "dependencies": [
        "trading-skills"
    ]
}

Risk Assessment

Calculate risk metrics for stocks and positions.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/risk.py SYMBOL [--period PERIOD] [--position-size SIZE]

Arguments

  • SYMBOL - Ticker symbol
  • --period - Analysis period: 1mo, 3mo, 6mo, 1y (default: 1y)
  • --position-size - Dollar amount for position-specific metrics (optional)

Output

Returns JSON with:

  • volatility - Historical volatility (annualized)
  • beta - Beta vs SPY
  • var_95 - 95% Value at Risk (daily)
  • var_99 - 99% Value at Risk (daily)
  • max_drawdown - Maximum drawdown in period
  • sharpe_ratio - Risk-adjusted return
  • position_risk - If position-size provided, dollar VaR

Explain what the risk metrics mean and suggest position sizing if relevant.

Dependencies

  • numpy
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
扫描股票并基于SMA、RSI、MACD等指标按综合得分排名,识别看涨趋势。适用于用户请求扫描看涨股、查找趋势股或按动量排序代码时。
扫描看涨股票 查找趋势股 按动量排序代码
.claude/skills/scanner-bullish/SKILL.md
npx skills add staskh/trading_skills --skill scanner-bullish -g -y
SKILL.md
Frontmatter
{
    "name": "scanner-bullish",
    "description": "Scan stocks for bullish trends using technical indicators (SMA, RSI, MACD, ADX). Use when user asks to scan for bullish stocks, find trending stocks, or rank symbols by momentum.",
    "dependencies": [
        "trading-skills"
    ]
}

Bullish Scanner

Scans symbols for bullish trends and ranks them by composite score.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/scan.py SYMBOLS [--top N] [--period PERIOD]

Arguments

  • SYMBOLS - Comma-separated ticker symbols (e.g., AAPL,MSFT,GOOGL,NVDA)
  • --top - Number of top results to return (default: 30)
  • --period - Historical period for analysis: 1mo, 3mo, 6mo (default: 3mo)

Scoring System (max ~9.5 points)

Indicator Condition Points
SMA20 Price > SMA20 +1.0
SMA50 Price > SMA50 +1.0
RSI 50-70 (bullish) +1.0
30-50 (neutral) +0.5
<30 (oversold) +0.25
MACD MACD > Signal +1.0
Histogram rising +0.5
EMA9/21 EMA9 > EMA21 (golden cross) +0.5
EMA9 < EMA21 (death cross) -0.25
Dual crossover Both up, both ≤10 days +1.0
Both up, any age +0.5
Both down, both ≤10 days -1.0
Both down, any age -0.5
Directions conflict -0.5
ADX >25 with +DI > -DI +1.5
+DI > -DI only +0.5
Momentum period return / 20 -1 to +2

Output

Returns JSON with:

  • scan_date - Timestamp of scan
  • symbols_scanned - Total symbols analyzed
  • results - Array sorted by score (highest first):
    • symbol, score, price
    • next_earnings, earnings_timing (BMO/AMC)
    • period_return_pct, pct_from_sma20, pct_from_sma50
    • rsi, macd, macd_signal, macd_hist, adx, dmp, dmn
    • ema9, ema21 — current EMA9 and EMA21 values
    • ema_crossover - Most recent EMA9/EMA21 crossover (or null if none found):
      • direction - "up" (EMA9 crossed above EMA21 = bullish) or "down" (crossed below = bearish)
      • days_ago - Trading days since the crossover bar (0 = happened in the most recent bar)
    • macd_crossover - Most recent MACD crossover (or null if none found):
      • direction - "up" (MACD crossed above signal = bullish) or "down" (crossed below = bearish)
      • days_ago - Trading days since the crossover bar (0 = happened in the most recent bar)
    • signals - List of triggered conditions

EMA Crossover Interpretation

  • EMA9 > EMA21 with small days_ago (0-5): fresh golden cross — short-term momentum confirmed
  • EMA9 just crossed below EMA21: death cross — short-term momentum turning negative
  • EMA9 crossover lagging MACD crossover by days: normal — MACD leads, EMA confirms
  • null: EMA9/21 relationship unchanged throughout the period

MACD Crossover Interpretation

  • direction: "up" with small days_ago (0-5): fresh bullish crossover — early entry signal
  • direction: "up" from a deeply negative signal: recovery from correction
  • direction: "down": momentum has turned bearish regardless of score
  • null: no sign change found in the period — trend has been consistently one-directional

Examples

# Scan a few symbols
uv run python scripts/scan.py AAPL,MSFT,GOOGL,NVDA,TSLA

# Get top 10 from larger list
uv run python scripts/scan.py AAPL,MSFT,GOOGL,NVDA,TSLA,AMD,AMZN,META --top 10

# Use 6-month lookback
uv run python scripts/scan.py AAPL,MSFT,GOOGL --period 6mo

Interpretation

  • Score > 6: Strong bullish trend
  • Score 4-6: Moderate bullish
  • Score 2-4: Neutral/weak
  • Score < 2: Bearish or no trend

Dependencies

  • pandas
  • pandas-ta
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
扫描并评估PMCC(穷人备兑看涨期权)策略适用标的。通过分析LEAPS和短期期权的Delta、流动性、价差、隐含波动率、收益率、趋势及财报时间,计算综合评分以筛选最优交易机会。
询问PMCC候选股 询问对角价差策略 询问LEAPS策略
.claude/skills/scanner-pmcc/SKILL.md
npx skills add staskh/trading_skills --skill scanner-pmcc -g -y
SKILL.md
Frontmatter
{
    "name": "scanner-pmcc",
    "description": "Scan stocks for Poor Man's Covered Call (PMCC) suitability. Analyzes LEAPS and short call options for delta, liquidity, spread, IV, yield, trend direction, and earnings proximity. Use when user asks about PMCC candidates, diagonal spreads, or LEAPS strategies.",
    "dependencies": [
        "trading-skills"
    ]
}

PMCC Scanner

Finds optimal Poor Man's Covered Call setups by scoring symbols on option chain quality.

What is PMCC?

Buy deep ITM LEAPS call (delta ~0.80) + Sell short-term OTM call (delta ~0.20) against it. Cheaper alternative to covered calls.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/scan.py SYMBOLS [options]

Arguments

  • SYMBOLS - Comma-separated tickers or path to JSON file from bullish scanner
  • --min-leaps-days - Minimum LEAPS expiration in days (default: 270 = 9 months)
  • --leaps-delta - Target LEAPS delta (default: 0.80)
  • --short-delta - Target short call delta (default: 0.20)
  • --output - Save results to JSON file (use this; Claude generates the report from the JSON)
  • --report - Save auto-generated markdown to file (programmatic fallback only — prefer Claude-generated reports)

Scoring System (max possible: 14, range: -4 to 14)

Category Condition Points
Delta Accuracy LEAPS within ±0.05 +2
LEAPS within ±0.10 +1
Short within ±0.05 +1
Short within ±0.10 +0.5
Liquidity LEAPS vol+OI > 100 +1
LEAPS vol+OI > 20 +0.5
Short vol+OI > 500 +1
Short vol+OI > 100 +0.5
Spread LEAPS spread < 5% +1
LEAPS spread < 10% +0.5
Short spread < 10% +1
Short spread < 20% +0.5
IV Level 25-50% (ideal) +2
20-60% +1
Yield Annual > 50% +2
Annual > 30% +1
Trend Price > SMA50 +1 / -1
RSI > 50 +0.5 / -0.5
MACD > signal +0.5 / -0.5
Earnings Next earnings > 45 days +1.0
Earnings within 45 days -1.0
Earnings within short expiry -2.0

Output

Returns JSON with:

  • criteria - Scan parameters used
  • results - Array sorted by score:
    • symbol, price, iv_pct, pmcc_score, max_possible_score (always 14)
    • leaps - expiry, strike, delta, iv (calculated from bid/ask), last_price, bid/ask, spread%, volume, OI
    • short - expiry, strike, delta, iv (calculated from bid/ask), last_price, bid/ask, spread%, volume, OI
    • earnings_date - next earnings date (YYYY-MM-DD) or null
    • metrics - net_debit, short_yield%, annual_yield%, capital_required
    • score_breakdown - every scoring component as a <name>_delta (float) + <name> (explanation string) pair:
      • Base: leaps_delta, short_delta, leaps_liquidity, short_liquidity, leaps_spread, short_spread, iv, yield
      • Trend: trend_delta, trend (per-indicator dict)
      • Earnings: earnings_delta, earnings
      • All _delta values sum to pmcc_score
  • errors - Symbols that failed (no options, insufficient data)

Report Generation

When the user asks for a report, a written analysis, or a saved document:

  1. Run the scanner with --output to capture JSON data:

    uv run python scripts/scan.py SYMBOLS --output sandbox/PMCC_Scan_YYYY-MM-DD_HHmm.json
    
  2. Read the JSON output.

  3. Generate the markdown report yourself using the template defined in templates/markdown-template.md. Do not use the --report flag — that produces mechanical string output. Claude-generated reports include real analysis, contextual warnings, and trader-relevant narrative.

  4. Save the generated markdown to sandbox/PMCC_Scan_YYYY-MM-DD_HHmm.md (match the JSON timestamp).

  5. Display the full report to the user.

Examples

# Scan specific symbols
uv run python scripts/scan.py AAPL,MSFT,GOOGL,NVDA

# Scan and save JSON for report generation
uv run python scripts/scan.py AAPL,MSFT,GOOGL --output sandbox/PMCC_Scan_2026-01-15_1430.json

# Use output from bullish scanner
uv run python scripts/scan.py bullish_results.json

# Custom delta targets
uv run python scripts/scan.py AAPL,MSFT --leaps-delta 0.70 --short-delta 0.15

# Longer LEAPS (1 year minimum)
uv run python scripts/scan.py AAPL,MSFT --min-leaps-days 365

IV Calculation

IV is always computed from market price data via Black-Scholes, never taken from Yahoo Finance's impliedVolatility column:

  • During trading hours: IV derived from bid/ask mid price
  • Off-hours (bid=ask=0): IV derived from last price, using the option's last trade timestamp as the pricing moment (not current wall-clock time)

This applies to both compute_atm_iv (used for scanner baseline IV) and per-option delta calculations.

Key Constraints

  • Short strike must be above LEAPS strike
  • Options with bid = 0 and no last price are skipped
  • Moderate IV (25-50%) scores highest

Interpretation

  • Score > 12: Excellent candidate (strong structure + bullish trend + clear earnings runway)
  • Score 10-12: Good candidate
  • Score 6-10: Acceptable with caveats
  • Score < 6: Poor structure, bearish trend, or earnings risk
  • max_possible_score is always 14 — use pmcc_score / max_possible_score to gauge how close a candidate is to perfect

Dependencies

  • numpy
  • pandas
  • scipy
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
分析垂直价差、铁鹰、跨式及宽跨式等期权策略。支持计算成本、最大盈亏、盈亏平衡点及盈利概率,并提供风险收益解释与适用场景建议。
用户询问期权价差策略分析 用户提及垂直价差、铁鹰、跨式或宽跨式
.claude/skills/spread-analysis/SKILL.md
npx skills add staskh/trading_skills --skill spread-analysis -g -y
SKILL.md
Frontmatter
{
    "name": "spread-analysis",
    "description": "Analyze option spread strategies like vertical spreads, iron condors, straddles, strangles. Use when user asks about spreads, multi-leg strategies, vertical spread, iron condor, straddle, strangle, or strategy analysis.",
    "dependencies": [
        "trading-skills"
    ]
}

Spread Analysis

Analyze multi-leg option strategies.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/spreads.py SYMBOL --strategy STRATEGY --expiry YYYY-MM-DD [options]

Strategies and Options

Vertical Spread (bull/bear call/put spread):

uv run python scripts/spreads.py AAPL --strategy vertical --expiry 2026-01-16 --type call --long-strike 180 --short-strike 185

Straddle (long call + long put at same strike):

uv run python scripts/spreads.py AAPL --strategy straddle --expiry 2026-01-16 --strike 180

Strangle (long call + long put at different strikes):

uv run python scripts/spreads.py AAPL --strategy strangle --expiry 2026-01-16 --put-strike 175 --call-strike 185

Iron Condor (sell strangle + buy wider strangle):

uv run python scripts/spreads.py AAPL --strategy iron-condor --expiry 2026-01-16 --put-short 175 --put-long 170 --call-short 185 --call-long 190

Output

Returns JSON with:

  • strategy - Strategy name and legs
  • cost - Net debit or credit
  • max_profit - Maximum potential profit
  • max_loss - Maximum potential loss
  • breakeven - Breakeven price(s)
  • probability - Estimated probability of profit (based on IV)

Explain the risk/reward and when this strategy is appropriate.

Dependencies

  • pandas
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
获取任意股票代码的实时股票报价,包括价格、成交量、涨跌幅、市值及52周区间。适用于查询当前股价或基础股票信息的场景。
用户询问某只股票的当前价格 用户请求查看股票的基本行情数据
.claude/skills/stock-quote/SKILL.md
npx skills add staskh/trading_skills --skill stock-quote -g -y
SKILL.md
Frontmatter
{
    "name": "stock-quote",
    "description": "Get real-time stock quote with price, volume, change, market cap, and 52-week range for any ticker symbol. Use when user asks about current stock price, quote, or basic stock info.",
    "dependencies": [
        "trading-skills"
    ]
}

Stock Quote

Fetch current stock data from Yahoo Finance.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

Run the quote script with the ticker symbol:

uv run python scripts/quote.py SYMBOL

Replace SYMBOL with the requested ticker (e.g., AAPL, MSFT, TSLA, SPY).

Output

The script outputs JSON with:

  • symbol, name, price, change, change_percent
  • volume, avg_volume, market_cap
  • high_52w, low_52w, pe_ratio, dividend_yield

Present the data in a readable format. Highlight significant moves (>2% change).

Dependencies

  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
计算RSI、MACD等技术指标及风险指标,支持多股票分析与财报数据。新增相关性分析功能,用于评估资产间价格关联度以辅助分散投资,需使用纽约时区处理时间数据。
用户询问技术指标如RSI、MACD、布林带等 请求进行股票或投资组合的相关性分析
.claude/skills/technical-analysis/SKILL.md
npx skills add staskh/trading_skills --skill technical-analysis -g -y
SKILL.md
Frontmatter
{
    "name": "technical-analysis",
    "description": "Compute technical indicators like RSI, MACD, Bollinger Bands, SMA, EMA for a stock. Use when user asks about technical analysis, indicators, RSI, MACD, moving averages, overbought\/oversold, or chart analysis.",
    "dependencies": [
        "trading-skills"
    ]
}

Technical Analysis

Compute technical indicators using pandas-ta. Supports multi-symbol analysis and earnings data.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python scripts/technicals.py SYMBOL [--period PERIOD] [--indicators INDICATORS] [--earnings]

Arguments

  • SYMBOL - Ticker symbol or comma-separated list (e.g., AAPL or AAPL,MSFT,GOOGL)
  • --period - Historical period: 1mo, 3mo, 6mo, 1y (default: 3mo)
  • --indicators - Comma-separated list: rsi,macd,bb,sma,ema,atr,adx (default: all)
  • --earnings - Include earnings data (upcoming date + history)

Output

Single symbol returns:

  • price - Current price and recent change
  • indicators - Computed values for each indicator
  • risk_metrics - Volatility (annualized %) and Sharpe ratio
  • signals - Buy/sell signals based on indicator levels
  • earnings - Upcoming date and EPS history (if --earnings)

Multiple symbols returns:

  • results - Array of individual symbol results

Interpretation

  • RSI > 70 = overbought, RSI < 30 = oversold
  • MACD crossover = momentum shift
  • Price near Bollinger Band = potential reversal
  • Golden cross (SMA20 > SMA50) = bullish
  • ADX > 25 = strong trend
  • Sharpe ratio > 1 = good risk-adjusted returns, > 2 = excellent
  • Volatility (annualized) = standard deviation of returns scaled to annual basis

Examples

# Single symbol with all indicators
uv run python scripts/technicals.py AAPL

# Multiple symbols
uv run python scripts/technicals.py AAPL,MSFT,GOOGL

# With earnings data
uv run python scripts/technicals.py NVDA --earnings

# Specific indicators only
uv run python scripts/technicals.py TSLA --indicators rsi,macd

Correlation Analysis

Compute price correlation matrix between multiple symbols for diversification analysis.

Instructions

uv run python scripts/correlation.py SYMBOLS [--period PERIOD]

Arguments

  • SYMBOLS - Comma-separated ticker symbols (minimum 2)
  • --period - Historical period: 1mo, 3mo, 6mo, 1y (default: 3mo)

Output

  • symbols - List of symbols analyzed
  • period - Time period used
  • correlation_matrix - Nested dict with correlation values between all pairs

Interpretation

  • Correlation near 1.0 = highly correlated (move together)
  • Correlation near -1.0 = negatively correlated (move opposite)
  • Correlation near 0 = uncorrelated (independent movement)
  • For diversification, prefer low/negative correlations

Examples

# Portfolio correlation
uv run python scripts/correlation.py AAPL,MSFT,GOOGL,AMZN

# Sector comparison
uv run python scripts/correlation.py XLF,XLK,XLE,XLV --period 6mo

# Check hedge effectiveness
uv run python scripts/correlation.py SPY,GLD,TLT

Dependencies

  • numpy
  • pandas
  • pandas-ta
  • yfinance

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills
扫描标的期权链以识别机构级大额交易。通过Yahoo Finance粗筛异常合约,再利用Massive API精确检测秒级资金流出异常,输出鲸鱼事件详情及汇总数据。
询问特定代码的异常期权活动 查询大型机构块状交易 分析机构期权资金流向
.claude/skills/whale-hunting/SKILL.md
npx skills add staskh/trading_skills --skill whale-hunting -g -y
SKILL.md
Frontmatter
{
    "name": "whale-hunting",
    "description": "Detect institutional whale activity in options for a given underlying. Use when the user asks about unusual options activity, large block trades, whale trades, or institutional options flow for a specific symbol.",
    "dependencies": [
        "trading-skills"
    ]
}

Whale Hunting

Scans option chains for a given underlying to identify institutional-sized trades using a two-step approach:

  1. Crude scan (Yahoo Finance) — finds contracts with anomalous daily investment vs the rest of the chain.
  2. Precise drill-down (Massive API) — fetches per-second bars for each candidate and flags seconds with outlier dollar invested.

Instructions

Note: If uv is not installed or pyproject.toml is not found, replace uv run python with python in all commands below.

uv run python .claude/skills/whale-hunting/scripts/whale_hunting.py SYMBOL [--months N] [--date YYYY-MM-DD] [--sigma F] [--sigma-z F] [--summary]

Arguments

  • SYMBOL — Underlying ticker (e.g. AAPL, NVDA, SPY)
  • --months — Max months until option expiration to consider (default: 2)
  • --date — Trading date to analyze in YYYY-MM-DD format (default: latest trading day)
  • --sigma — Std-deviation multiplier for crude outlier threshold (default: 3.0)
  • --sigma-z — Modified Z-Score threshold for per-second small-sample detection (default: 3.5)
  • --summary — Also compute per-ticker summary and include it in the JSON output

Output

Returns JSON with:

  • underlying — The scanned symbol
  • trading_date — Date analyzed
  • source"massive" (per-second data) or "yahoo only" (daily chain data)
  • total_whales — Total whale events found
  • total_call_invested — Sum of invested dollars in call whale events
  • total_put_invested — Sum of invested dollars in put whale events
  • call_put_ratio — Call invested / put invested (null if no puts)
  • whales — List of whale events:
    • timestamp, ticker, type, strike, expiry
    • close, volume, transactions, invested, break_even
  • summary (present only when --summary is passed) — List of per-ticker aggregates:
    • ticker, type, strike, expiry, whale_count, total_invested, break_even

Examples

# Hunt whales for AAPL (latest trading day)
uv run python .claude/skills/whale-hunting/scripts/whale_hunting.py AAPL

# Hunt whales for NVDA on a specific date
uv run python .claude/skills/whale-hunting/scripts/whale_hunting.py NVDA --date 2026-03-13

# With per-ticker summary
uv run python .claude/skills/whale-hunting/scripts/whale_hunting.py HOOD --months 3 --summary

# Looser detection threshold
uv run python .claude/skills/whale-hunting/scripts/whale_hunting.py SPY --sigma 2.0

Reporting

After running the script, present the results as follows.

Header line:

Whale activity for {underlying} on {trading_date} — source: {source} Call flow: ${total_call_invested:,.0f} | Put flow: ${total_put_invested:,.0f} | C/P ratio: {call_put_ratio:.2f}

When --summary was requested, render the summary array as a table:

Time (ET) Ticker Type Strike Expiry # Events Total Invested Break Even
{timestamp} {ticker} {type} {strike} {expiry} {whale_count} ${total_invested:,.0f} {break_even}

Sort by total_invested descending. For multi-event rows use the time range of first–last event (e.g. 11:46–12:33).

Interpretation guidance:

  • source: "massive" — High-confidence; per-second block trade data from Massive API
  • source: "yahoo only" — Fallback; daily-level data (Massive API key missing or no intraday data)
  • Low C/P ratio (< 0.5) — Bearish institutional positioning
  • High C/P ratio (> 2.0) — Bullish institutional positioning
  • transactions: 1 — Single block trade; strongest whale signal

Requirements

  • MASSIVE_API_KEY environment variable for per-second data. Without it, falls back to Yahoo Finance daily data.

Timezone

All timestamps and time-based calculations must use the America/New_York timezone. All JSON output must include generated_at (NY time string) and data_delay fields.

Dependencies: trading-skills

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-13 22:08
浙ICP备14020137号-1 $mapa de visitantes$