docs: complete project research

This commit is contained in:
Filipe Salvio 2026-03-29 19:10:03 -03:00
parent 52af95ab40
commit 2990b43b57
5 changed files with 683 additions and 0 deletions

View File

@ -0,0 +1,163 @@
# Architecture Patterns
**Domain:** Options trading analysis module for multi-agent AI trading system
**Researched:** 2026-03-29
## Recommended Architecture
The options module plugs into the existing TradingAgents architecture as a **parallel agent team** alongside the stock analysis team. It follows the same patterns: agent factory closures, LangGraph StateGraph, vendor-routed data layer.
### Component Boundaries
| Component | Responsibility | Communicates With |
|-----------|---------------|-------------------|
| `tradingagents/dataflows/tradier.py` | Options chain retrieval, expirations, strikes via Tradier REST API | Agent tools, config |
| `tradingagents/dataflows/tastytrade.py` | Real-time Greeks streaming via DXLink WebSocket (optional) | Agent tools, config |
| `tradingagents/options/greeks.py` | 2nd/3rd order Greeks calculation (Charm, Vanna, Volga) from 1st-order + spot | Greeks analysis agent |
| `tradingagents/options/volatility.py` | IV Rank, IV Percentile, SVI surface fitting, vol skew metrics | Volatility analysis agent |
| `tradingagents/options/gex.py` | GEX computation, Call/Put Walls, gamma flip zone, Vanna/Charm exposure | GEX analysis agent |
| `tradingagents/options/flow.py` | Volume/OI analysis, unusual activity detection heuristics | Flow analysis agent |
| `tradingagents/options/strategies.py` | Multi-leg strategy construction, P/L profiles, PoP estimation | Strategy selection agent |
| `tradingagents/options/scoring.py` | MenthorQ-style composite Options Score (0-5) | Options portfolio manager |
| `tradingagents/agents/options/` | Agent factory functions for each options analyst role | LangGraph StateGraph |
| `tradingagents/graph/options_team.py` | LangGraph StateGraph for the options analysis pipeline | Main graph (parallel branch) |
### Data Flow
```
User input (ticker, date range)
|
v
[Tradier API] --> options chain DataFrame (strikes, bids, asks, Greeks, IV, OI)
|
+---> [Volatility Agent] --> IV Rank, IV Percentile, vol skew, SVI surface
|
+---> [Greeks Agent] --> 2nd-order Greeks (Charm, Vanna, Volga) per strike
|
+---> [GEX Agent] --> Net GEX, Call/Put Walls, gamma flip zone, regime
|
+---> [Flow Agent] --> Unusual activity signals, volume/OI anomalies
|
v
[Strategy Selection Agent] <-- all analysis outputs
|
v
[Options Debate] (bull vs bear on options thesis, configurable rounds)
|
v
[Options Portfolio Manager] --> final recommendation
|
v
Output: specific contracts + alternative ranges + reasoning chain
```
## Patterns to Follow
### Pattern 1: Agent Factory Closures (existing pattern)
**What:** Each agent is created via a `create_*()` closure that captures LLM client and tools.
**When:** Always -- this is the established pattern in the codebase.
**Example:**
```python
def create_volatility_analyst(llm_client, tools):
"""Create volatility analysis agent with options-specific tools."""
system_prompt = VOLATILITY_ANALYST_PROMPT
def volatility_analyst(state):
chain_data = state["options_chain"]
# Compute IV metrics using tools
iv_rank = tools["compute_iv_rank"](chain_data, state["ticker"])
# LLM interprets the metrics
response = llm_client.invoke([
SystemMessage(content=system_prompt),
HumanMessage(content=format_iv_analysis(iv_rank, chain_data))
])
return {"volatility_analysis": response.content}
return volatility_analyst
```
### Pattern 2: Vendor-Routed Data Layer (existing pattern)
**What:** Data retrieval goes through a routing layer that selects the vendor based on config.
**When:** For all options data retrieval -- Tradier is primary, tastytrade is fallback/supplement.
**Example:**
```python
# In tradingagents/dataflows/config.py (extend existing)
# Add "tradier" to data_vendors options
def get_options_chain(ticker, expiration, config):
vendor = config.get("options_vendor", "tradier")
if vendor == "tradier":
return tradier.get_chain(ticker, expiration)
elif vendor == "tastytrade":
return tastytrade.get_chain(ticker, expiration)
```
### Pattern 3: Computation Modules as Pure Functions
**What:** GEX, Greeks, vol surface calculations are stateless pure functions that take DataFrames and return DataFrames.
**When:** All options math modules.
**Why:** Testable without LLM calls, cacheable, composable.
```python
# tradingagents/options/gex.py
def compute_gex(chain_df: pd.DataFrame, spot: float) -> pd.DataFrame:
"""Pure function: chain DataFrame in, GEX DataFrame out."""
chain_df["call_gex"] = chain_df["gamma"] * chain_df["open_interest"] * 100 * spot**2 * 0.01
chain_df["put_gex"] = -chain_df["gamma"] * chain_df["open_interest"] * 100 * spot**2 * 0.01
# ... aggregate, find walls, flip zone
return gex_df
```
### Pattern 4: 5-Tier Rating Scale (existing pattern)
**What:** All analysis outputs use BUY/OVERWEIGHT/HOLD/UNDERWEIGHT/SELL scale.
**When:** Options agents should output ratings consistent with existing stock analysts.
**Adaptation:** Options-specific interpretation:
- BUY = strong bullish options position recommended (long calls, bull spreads)
- OVERWEIGHT = moderately bullish (covered calls, bull put spreads)
- HOLD = neutral strategies (iron condors, straddles if high IV)
- UNDERWEIGHT = moderately bearish (bear call spreads, protective puts)
- SELL = strong bearish (long puts, bear spreads)
## Anti-Patterns to Avoid
### Anti-Pattern 1: Monolithic Options Agent
**What:** Single agent that does all options analysis (Greeks + GEX + flow + strategy).
**Why bad:** Unmanageable prompts, impossible to debug, cannot run analyses in parallel.
**Instead:** Separate specialized agents with focused prompts, composed via LangGraph.
### Anti-Pattern 2: LLM Doing Math
**What:** Asking the LLM to calculate Greeks, GEX, or IV metrics.
**Why bad:** LLMs are unreliable at arithmetic. A single wrong calculation cascades into bad recommendations.
**Instead:** All math in Python (blackscholes, numpy, scipy). LLM only interprets pre-computed results.
### Anti-Pattern 3: Hardcoded Strike Selection
**What:** Agent tools that select specific strikes based on rigid rules (e.g., "always pick ATM +/- 2 strikes").
**Why bad:** Different strategies need different strike selection logic. Iron condor wings vs vertical spread width depend on IV, premium targets, and risk tolerance.
**Instead:** Provide the LLM agent with a range of strikes and their computed metrics; let it reason about selection within the strategy context.
### Anti-Pattern 4: Synchronous Tastytrade Streaming in Batch Flow
**What:** Starting a DXLink WebSocket connection for every `propagate()` call.
**Why bad:** WebSocket setup overhead (auth, handshake, subscription) for a single snapshot is wasteful. Adds 2-5 seconds per call.
**Instead:** Use Tradier REST for batch flow. Only use tastytrade streaming if building a persistent session or needing sub-minute freshness.
## Scalability Considerations
| Concern | Current (single ticker) | Multi-ticker (10 tickers) | High volume (50+ tickers) |
|---------|------------------------|--------------------------|---------------------------|
| API rate limits | Tradier: ~2 req/ticker (chain + expirations), well within 120 req/min | 20 requests, still fine | 100+ requests, need queuing/throttling |
| Chain data size | ~200 strikes per expiry, 5-8 expiries = 1000-1600 rows | 10x = 10-16K rows, fine in memory | 50x = manageable but cache aggressively |
| GEX computation | Sub-second numpy vectorization | Still sub-second | Still sub-second; numpy handles millions of rows |
| LLM calls per analysis | ~6 agents x 1 call each = 6 LLM calls | 60 LLM calls, significant latency | Need batching or parallel execution |
| Tastytrade WebSocket | Single subscription, minimal overhead | 10 subscriptions, fine | May hit subscription limits |
## Sources
- Existing codebase patterns in `tradingagents/agents/`, `tradingagents/graph/`, `tradingagents/dataflows/`
- [LangGraph StateGraph documentation](https://langchain-ai.github.io/langgraph/)
- [Tradier API rate limits](https://docs.tradier.com/)

View File

@ -0,0 +1,89 @@
# Feature Landscape
**Domain:** Options trading analysis module for multi-agent AI trading system
**Researched:** 2026-03-29
## Table Stakes
Features users expect. Missing = product feels incomplete.
| Feature | Why Expected | Complexity | Notes |
|---------|--------------|------------|-------|
| Options chain retrieval (strikes, expirations, bid/ask) | Cannot analyze options without the data | Low | Tradier API, single endpoint |
| 1st-order Greeks display (Delta, Gamma, Theta, Vega) | Every options platform shows these | Low | Tradier returns these via ORATS |
| Implied volatility per contract | Fundamental to options valuation | Low | Tradier returns bid_iv, mid_iv, ask_iv |
| IV Rank / IV Percentile | Core metric for deciding whether to sell or buy premium | Medium | Requires 52-week IV history; Tradier historical data or yfinance for underlying HV |
| Options strategy recommendation (verticals, iron condors, straddles) | The whole point of the module | High | LLM agent synthesis from Greeks + IV + directional bias |
| Max profit/loss and breakeven calculation | Users need to understand risk before entering | Medium | Arithmetic on strike prices and premiums for each strategy type |
| DTE-based filtering | Standard workflow: filter by 30-60 DTE for income strategies | Low | Simple date math on expiration dates |
| Probability of profit (PoP) estimation | Expected by anyone familiar with tastytrade methodology | Medium | Approximated from delta (1 - delta for short options) or from IV |
## Differentiators
Features that set product apart. Not expected, but valued.
| Feature | Value Proposition | Complexity | Notes |
|---------|-------------------|------------|-------|
| 2nd-order Greeks (Charm, Vanna, Volga) | Most retail platforms only show 1st-order; this provides institutional-level insight | Medium | Compute via blackscholes library from spot + 1st-order Greeks |
| Gamma Exposure (GEX) analysis with dealer positioning | SpotGamma-style analysis is premium ($199+/mo); providing this free is high-value | Medium | Numpy vectorized computation; interpretation via LLM agent |
| Volatility surface construction (SVI fitting) | Visual and quantitative understanding of vol skew and term structure | High | SVI calibration via scipy; requires enough strikes per expiration |
| Gamma flip zone / Vol Trigger identification | Identifies price levels where market maker hedging shifts from stabilizing to destabilizing | Medium | Derived from cumulative GEX sign change |
| Call Wall / Put Wall levels | Support/resistance levels derived from options positioning | Low | Max gamma exposure strikes from GEX computation |
| Unusual options activity detection | Identifies potential smart money positioning | Medium | Volume/OI heuristics; limited by lack of trade-level data |
| TastyTrade methodology rules engine | Proven decision framework (IVR thresholds, 45 DTE entry, 21 DTE management, 50% profit targets) | Medium | Rules-based logic layer feeding into strategy selection agent |
| Multi-leg strategy construction with specific contracts | Most analysis tools stop at "consider a put spread"; this names exact contracts | High | Agent must select strikes, expirations, and legs based on all analysis |
| Transparent reasoning chain | Shows WHY each strategy was selected, educational value | Medium | LLM agent chain-of-thought exposed to user |
| MenthorQ-style composite scoring (0-5 Options Score) | Single number summarizing options environment for quick decisions | Medium | Composite of IV rank, GEX regime, flow signals, vol skew |
## Anti-Features
Features to explicitly NOT build.
| Anti-Feature | Why Avoid | What to Do Instead |
|--------------|-----------|-------------------|
| Order execution / broker integration | Scope creep; regulatory complexity; analysis-only mandate | Output recommendation with contract symbols users can copy to their broker |
| Real-time streaming dashboard | Project uses batch `propagate()` flow; streaming requires different architecture | Provide point-in-time snapshots; tastytrade streaming is for data freshness, not live UI |
| 0DTE strategy analysis | Requires real-time infrastructure, sub-second data; batch analysis is stale before execution | Focus on 7-90 DTE strategies where hourly data refresh is sufficient |
| Historical IV surface storage | Requires ORATS subscription ($$$) or building own historical database | Use current IV surface; flag historical context as future enhancement |
| Options backtesting engine | Separate domain; options backtesting requires historical vol surfaces, fill simulation | Defer to future project; existing backtrader dependency is for equities |
| Custom volatility models (Heston, local vol) | Over-engineering; SVI is sufficient for equity options smile fitting | Use SVI parametric model; only consider Heston if pricing exotics |
| Portfolio-level Greeks aggregation | Would need to track user positions; analysis-only module has no position state | Analyze individual strategies, not portfolios |
## Feature Dependencies
```
Options chain retrieval --> 1st-order Greeks display
Options chain retrieval --> IV per contract --> IV Rank/Percentile
Options chain retrieval --> GEX computation --> Gamma flip zone, Call/Put Walls
1st-order Greeks + spot price --> 2nd-order Greeks (Charm, Vanna, Volga)
IV per contract --> Volatility surface (SVI fitting) --> Vol skew analysis
IV Rank/Percentile + directional bias --> TastyTrade rules engine --> Strategy selection
GEX regime + IV environment + flow signals --> Composite score (Options Score 0-5)
Strategy selection --> Multi-leg construction --> Max P/L + breakeven + PoP
All analysis agents --> Options debate --> Options portfolio manager --> Final recommendation
```
## MVP Recommendation
Prioritize (Phase 1 -- core analysis pipeline):
1. Options chain retrieval via Tradier API (foundation for everything)
2. 1st-order Greeks display (already in Tradier response)
3. IV Rank / IV Percentile calculation
4. GEX computation with Call/Put Wall levels
5. Basic strategy recommendation (single agent, 3-4 strategy types)
Defer:
- **2nd-order Greeks**: Phase 2 -- requires blackscholes library integration
- **Volatility surface (SVI)**: Phase 2 -- complex calibration, needs robust error handling
- **TastyTrade rules engine**: Phase 2 -- rules are well-defined but need IV Rank as input
- **Unusual activity detection**: Phase 2 -- limited by data availability without trade-level feed
- **Multi-leg specific contracts**: Phase 2 -- needs strategy selection working first
- **Composite scoring**: Phase 3 -- needs all analysis components as inputs
- **Tastytrade streaming**: Phase 3 -- enhancement for data freshness, not core functionality
## Sources
- [SpotGamma GEX methodology](https://spotgamma.com/gamma-exposure-gex/)
- [TastyTrade methodology](https://developer.tastytrade.com/)
- [Tradier options chain endpoint](https://docs.tradier.com/reference/brokerage-api-markets-get-options-chains)
- [Unusual options activity heuristics](https://intrinio.com/blog/how-to-read-unusual-options-activity-7-easy-steps)

View File

@ -0,0 +1,107 @@
# Domain Pitfalls
**Domain:** Options trading analysis module for multi-agent AI trading system
**Researched:** 2026-03-29
## Critical Pitfalls
Mistakes that cause rewrites or major issues.
### Pitfall 1: Stale Greeks Leading to Wrong Recommendations
**What goes wrong:** Tradier's ORATS-sourced Greeks update hourly. During volatile markets, Greeks can shift significantly within that hour. An agent recommending a delta-neutral strategy based on stale deltas could suggest a position that is actually directionally biased.
**Why it happens:** Treating API-provided Greeks as real-time when they are snapshots.
**Consequences:** Wrong strategy recommendations; user loses money following stale analysis.
**Prevention:** Always display the Greeks timestamp from Tradier response. Include a staleness warning in agent output if Greeks are >30 minutes old. For the volatility agent, compute IV from current bid/ask prices using scipy rather than relying solely on API-provided IV.
**Detection:** Agent output includes delta-neutral recommendation but underlying has moved >1% since Greeks timestamp.
### Pitfall 2: SVI Calibration Failure on Illiquid Options
**What goes wrong:** SVI model calibration (5 parameters) fails or produces nonsensical results when there are few liquid strikes. Illiquid options have wide bid-ask spreads, making mid-price IV unreliable. The optimizer converges to a local minimum that produces arbitrage in the fitted surface.
**Why it happens:** SVI needs 5+ liquid strikes per expiration to calibrate well. Many stocks have illiquid far-OTM options.
**Consequences:** Garbage vol surface leads to wrong skew analysis; agent makes recommendations based on fitted IV that does not reflect reality.
**Prevention:** Filter strikes by minimum open interest (>100) and maximum bid-ask spread (< 30% of mid). Fall back to linear interpolation when <5 liquid strikes. Add arbitrage-free constraints to SVI calibration (Gatheral's no-butterfly-arbitrage conditions).
**Detection:** Fitted IV values that differ >10% from market mid IV at liquid strikes. Negative total variance at any point.
### Pitfall 3: GEX Sign Convention Confusion
**What goes wrong:** The GEX formula's sign convention for puts is a common source of bugs. Dealer gamma exposure from puts is negative (dealers are short puts, so they have negative gamma), but the formula `Net_GEX = sum(Call_GEX) - sum(Put_GEX)` already accounts for this. Getting the sign wrong inverts the entire analysis -- what should be a gamma wall becomes a flip zone and vice versa.
**Why it happens:** Different sources use different sign conventions. SpotGamma's published formula differs in sign treatment from some academic sources.
**Consequences:** Completely inverted market structure analysis. Agent tells user "market makers will buy the dip" when they will actually sell into it.
**Prevention:** Use a single, well-tested GEX function with explicit unit tests. Test against known SpotGamma outputs for SPY/SPX if available. The canonical formula: dealers are long gamma on calls they sold (positive GEX) and short gamma on puts they sold (negative GEX when viewed from dealer perspective).
**Detection:** Sanity check: for a typical equity, GEX should be positive at/above the current price and transition to negative below. If the opposite, the sign is wrong.
### Pitfall 4: Python Version Incompatibility with tastytrade SDK
**What goes wrong:** The tastytrade community SDK (tastyware/tastytrade v12.3.1) requires Python >=3.11. The project declares `requires-python = ">=3.10"`. If a user installs on Python 3.10, the tastytrade dependency will fail.
**Why it happens:** The project's minimum Python version is lower than the tastytrade SDK's requirement.
**Consequences:** Installation failure for Python 3.10 users; confusing error messages.
**Prevention:** Either bump `requires-python` to `>=3.11` or make tastytrade an optional dependency with graceful degradation (Tradier-only mode). Recommended: bump to >=3.11 since numpy/scipy latest versions also dropped 3.10.
**Detection:** CI testing on Python 3.10 would catch this immediately.
## Moderate Pitfalls
### Pitfall 1: LLM Hallucinating Option Contract Symbols
**What goes wrong:** When the LLM agent recommends specific contracts, it may hallucinate valid-looking but non-existent option symbols (wrong expiration dates, non-standard strikes).
**Prevention:** The strategy agent should select from actual contracts present in the chain data, not generate symbols from scratch. Pass the full list of available contracts to the agent and constrain output to only those symbols.
### Pitfall 2: IV Rank Calculation Window Ambiguity
**What goes wrong:** IV Rank and IV Percentile are often confused, and the lookback window (52 weeks vs 1 year vs rolling) affects the value significantly. Different sources define them differently.
**Prevention:** Be explicit about definitions in agent prompts and code:
- IV Rank = (Current IV - 52wk Low IV) / (52wk High IV - 52wk Low IV) -- range 0-100
- IV Percentile = % of trading days in the past year where IV was below current IV -- range 0-100
Use consistent 252-trading-day lookback. Document the definition in code comments.
### Pitfall 3: Options Expiration Date Edge Cases
**What goes wrong:** Not all options expire on the third Friday. Weekly options, quarterly options, end-of-month options, and index options (AM vs PM settlement) have different expiration rules. Assuming standard monthly expiration leads to wrong DTE calculations.
**Prevention:** Use the actual expiration dates returned by Tradier API rather than computing them. Never assume expiration day of week.
### Pitfall 4: GEX Across Expirations Without Weighting
**What goes wrong:** Naively summing GEX across all expirations treats a 1-day option the same as a 90-day option. Short-dated options have much higher gamma and dominate the GEX calculation, potentially masking important positioning at longer expirations.
**Prevention:** Weight GEX by relevance. SpotGamma focuses on the nearest 4 expirations. Consider computing GEX separately for 0-7 DTE, 7-30 DTE, and 30+ DTE buckets.
### Pitfall 5: Rate Limiting with Multiple Tradier Calls
**What goes wrong:** Each ticker analysis needs calls for: expirations list, chain per expiration (multiple), historical data. For a single ticker with 8 expirations, that is 9+ API calls. At 120 req/min, analyzing 10+ tickers hits limits.
**Prevention:** Cache expirations (they change weekly at most). Batch chain requests. Implement exponential backoff with retry. Consider only fetching the 4 nearest expirations (sufficient for most analysis per SpotGamma methodology).
## Minor Pitfalls
### Pitfall 1: Displaying Raw Greeks Without Context
**What goes wrong:** Showing "Delta: 0.45" without context is meaningless to many users.
**Prevention:** Agent should explain what the Greek means in the current context: "Delta of 0.45 means the option moves ~$0.45 for every $1 move in the underlying."
### Pitfall 2: Ignoring Dividends in Greeks Calculation
**What goes wrong:** Black-Scholes assumes no dividends. For dividend-paying stocks, computed Greeks (especially for long-dated options) will be slightly off.
**Prevention:** Use Black-Scholes-Merton (which accounts for continuous dividend yield) via the blackscholes library. Pass dividend yield as input parameter.
### Pitfall 3: Weekend/Holiday Theta Decay
**What goes wrong:** Theta is quoted per calendar day, but options do not decay linearly over weekends/holidays.
**Prevention:** Note in agent output that theta acceleration happens approaching expiration and that weekend theta is priced in on Friday afternoon.
## Phase-Specific Warnings
| Phase Topic | Likely Pitfall | Mitigation |
|-------------|---------------|------------|
| Tradier API integration | Sandbox vs production API differences (delayed data in sandbox) | Test with sandbox, document limitations, flag in output |
| Greeks computation (2nd order) | Numerical instability near expiration (gamma explosion) | Cap computed Greeks at reasonable bounds, warn on <3 DTE options |
| SVI calibration | Convergence failure on illiquid names | Fallback to interpolation, minimum liquidity filters |
| GEX implementation | Sign convention error | Comprehensive unit tests against known outputs |
| Flow detection | False positives on unusual activity (earnings, ex-div dates) | Check corporate calendar before flagging activity as "unusual" |
| Strategy recommendation | LLM recommending strategies inappropriate for IV environment | TastyTrade rules engine as guardrail (e.g., do not sell premium when IVR < 20) |
| Multi-leg construction | Recommending spreads wider than available liquidity | Check bid-ask spreads on recommended legs; warn if total spread cost is >10% of max profit |
## Sources
- [SpotGamma GEX methodology and sign conventions](https://spotgamma.com/gamma-exposure-gex/)
- [Gatheral SVI arbitrage-free conditions](https://mfe.baruch.cuny.edu/wp-content/uploads/2013/01/OsakaSVI2012.pdf)
- [Tradier API rate limits and sandbox](https://docs.tradier.com/)
- [tastytrade SDK Python requirements](https://pypi.org/project/tastytrade/)
- [IV Rank vs IV Percentile definitions](https://www.tastylive.com/)

149
.planning/research/STACK.md Normal file
View File

@ -0,0 +1,149 @@
# Technology Stack
**Project:** TradingAgents Options Trading Module
**Researched:** 2026-03-29
## Recommended Stack
### Options Data Providers
| Technology | Version | Purpose | Why | Confidence |
|------------|---------|---------|-----|------------|
| **Tradier REST API** (direct `requests`) | N/A (REST) | Options chains, strikes, expirations, 1st-order Greeks, IV | Returns delta/gamma/theta/vega/rho/phi + bid_iv/mid_iv/ask_iv/smv_vol via ORATS. Free sandbox. No SDK needed -- simple REST with `requests` (already a dependency). Hourly Greeks refresh is sufficient for batch analysis. | HIGH |
| **tastytrade** (tastyware community SDK) | >=12.3.1 | Real-time streaming Greeks, live quotes via DXLink WebSocket | Official `tastytrade-sdk-python` was archived March 2026. The `tastyware/tastytrade` community SDK is the de facto standard: 95%+ test coverage, full typing with Pydantic, async DXLink WebSocket streaming. Requires Python >=3.11 (project venv is 3.13, so no issue). | HIGH |
**Data provider strategy:** Tradier is the primary REST data source (chains, expirations, ORATS Greeks). Tastytrade is the streaming supplement for real-time Greeks updates. Both fit the existing vendor-routing pattern in `tradingagents/dataflows/`.
**API keys required:**
- `TRADIER_API_KEY` -- free sandbox at developer.tradier.com, production requires brokerage account
- `TASTYTRADE_USERNAME` / `TASTYTRADE_PASSWORD` -- requires tastytrade account (free to create)
### Greeks and Pricing Calculation
| Technology | Version | Purpose | Why | Confidence |
|------------|---------|---------|-----|------------|
| **blackscholes** | >=0.2.0 | 1st, 2nd, and 3rd order Greeks (Charm, Vanna, Volga/Vomma) | Actively maintained (Dec 2024 release), Python >=3.8, supports BSM + Black-76, up to 3rd-order Greeks out of the box. Lightweight, no heavy C dependencies. Covers the gap where Tradier API only provides 1st-order Greeks. | HIGH |
| **scipy** (optimize) | >=1.14.0 | IV solver (Brent's method), SVI curve fitting (least squares) | Already an indirect dependency via pandas/numpy ecosystem. `scipy.optimize.brentq` for IV root-finding, `scipy.optimize.minimize` for SVI parameter calibration. Battle-tested numerical methods. | HIGH |
| **numpy** | >=2.0.0 | Vectorized Greeks computation, GEX aggregation across strikes | Already an indirect dependency. All Greeks math and exposure aggregation should be vectorized with numpy for performance across full options chains (hundreds of strikes). | HIGH |
**Not recommended:**
- **py_vollib** (v1.0.1, last release 2017) -- effectively abandoned. The `blackscholes` package is newer, actively maintained, and covers more Greeks.
- **py-vollib-vectorized** (v0.1.1, last release 2021) -- depends on abandoned py_vollib, not maintained.
- **mibian** -- undocumented, minimal maintenance, limited to basic Greeks. `blackscholes` is strictly better.
- **QuantLib** (v1.41) -- massively over-engineered for this use case. 200+ MB compiled binary, complex C++ binding. Justified for interest rate derivatives or exotic options, not for equity options Greeks in an LLM agent pipeline. The vol surface modeling via SVI can be done with scipy alone.
### Volatility Surface Modeling
| Technology | Version | Purpose | Why | Confidence |
|------------|---------|---------|-----|------------|
| **scipy.optimize** | >=1.14.0 | SVI model calibration (5 params: a, b, rho, m, sigma) | SVI (Stochastic Volatility Inspired) is the industry standard for equity options vol smile fitting. Calibration is a nonlinear least-squares problem -- `scipy.optimize.minimize` with SLSQP or L-BFGS-B handles it well. No dedicated library needed. | MEDIUM |
| **scipy.interpolate** | >=1.14.0 | Interpolation across strikes/expirations for smooth vol surface | `RectBivariateSpline` or `griddata` for 2D interpolation across the (strike, expiration) grid. Standard approach when parametric SVI is overkill for some expirations. | HIGH |
| **matplotlib** | >=3.9.0 | Vol surface visualization (3D plots, heatmaps) | For debugging and analysis output. Optional -- only needed if generating visual reports. | HIGH |
**Approach:** Use SVI parametric fitting per-expiration to construct the volatility smile, then interpolate across expirations to build the full surface. This is the standard approach used in practice (confirmed by multiple 2025 implementations and academic comparisons).
**Not recommended:**
- **SABR model** -- better suited for interest rate derivatives. For equity options with discrete strikes and limited expirations, SVI is simpler and equally accurate. A 2025 thesis comparing SVI vs SABR on SPY/QQQ found comparable performance with SVI being easier to calibrate.
### Gamma Exposure (GEX) Computation
| Technology | Version | Purpose | Why | Confidence |
|------------|---------|---------|-----|------------|
| **numpy** | >=2.0.0 | Vectorized GEX calculation across all strikes/expirations | GEX formula is straightforward: `GEX_per_strike = Gamma * OI * 100 * Spot^2 * 0.01`, then `Net_GEX = sum(Call_GEX) - sum(Put_GEX)`. Pure numpy vectorization handles the full chain in microseconds. | HIGH |
| **pandas** | >=2.3.0 | Structuring GEX output (strike-level breakdown, flip zones, walls) | Already a core dependency. GEX output is naturally tabular: per-strike gamma, cumulative GEX, call/put walls, flip zones. | HIGH |
**No external library needed.** GEX computation is arithmetic on options chain data. The SpotGamma methodology is documented:
- Net GEX across strikes identifies gamma walls (high absolute GEX = support/resistance)
- Sign flip in cumulative GEX identifies the "Vol Trigger" / gamma flip zone
- Call Wall = strike with max positive call gamma exposure
- Put Wall = strike with max negative put gamma exposure
The complexity is in interpretation (which the LLM agent handles), not computation.
### Options Flow / Unusual Activity Detection
| Technology | Version | Purpose | Why | Confidence |
|------------|---------|---------|-----|------------|
| **pandas** | >=2.3.0 | Volume/OI ratio analysis, sweep/block classification | Flow detection is data filtering: volume > threshold, volume/OI ratio > 1.25, relative volume vs historical average. Pure pandas operations. | HIGH |
| **Tradier API** (historical options) | N/A | Historical volume/OI baselines for relative volume calculation | Tradier provides historical options data to establish baselines. Without baselines, "unusual" has no reference point. | MEDIUM |
**Detection heuristics (no library needed):**
- Unusual activity: `volume / avg_daily_volume > 2.0` AND `volume / open_interest > 1.25`
- New position signal: `volume >> open_interest` (new positions being opened)
- Smart money proxy: large block trades (>100 contracts), sweeps across exchanges
- Put/call volume ratio spikes relative to historical norm
**Limitation:** Tradier's market data API does not provide trade-level data (individual fills, sweep detection). True sweep/block detection requires Level 2 or trade-by-trade data. The module should classify by volume patterns rather than individual trade types. Flag this as a known limitation.
### Supporting Libraries
| Library | Version | Purpose | When to Use | Confidence |
|---------|---------|---------|-------------|------------|
| **pydantic** | >=2.0 | Data models for options chain, Greeks, GEX output | Already an indirect dependency (via tastytrade SDK, LangChain). Use for typed data structures in the options module. | HIGH |
| **httpx** | >=0.27.0 | Async HTTP client for Tradier API | If async Tradier calls are needed alongside tastytrade's async DXLink. Otherwise `requests` (already a dependency) suffices for sync calls. | LOW |
| **python-dateutil** | >=2.9.0 | Options expiration date calculations (3rd Friday, weeklies) | Parsing and computing DTE, expiration cycles. Likely already an indirect dependency. | HIGH |
## Python Version Consideration
The project declares `requires-python = ">=3.10"` but the development venv runs Python 3.13. The tastytrade SDK requires `>=3.11`. Two options:
1. **Recommended:** Bump `requires-python` to `>=3.11` when adding the options module. This unlocks the tastytrade SDK and latest numpy/scipy without constraints.
2. **Alternative:** Keep `>=3.10` and make tastytrade an optional dependency. Tradier alone covers the core use case.
## Alternatives Considered
| Category | Recommended | Alternative | Why Not |
|----------|-------------|-------------|---------|
| Greeks calculation | blackscholes | py_vollib | Abandoned since 2017, no 2nd/3rd order Greeks |
| Greeks calculation | blackscholes | QuantLib | 200MB+ binary, C++ dependency, massive overkill for equity options |
| Greeks calculation | blackscholes | mibian | Minimal maintenance, no typing, limited Greek support |
| Vol surface | scipy SVI fitting | QuantLib SviInterpolatedSmileSection | QuantLib dependency not justified for SVI alone |
| Vol surface model | SVI | SABR | SABR better for rates; SVI simpler and equally accurate for equities |
| Tradier SDK | Direct requests | uvatradier | Thin wrapper adds dependency without meaningful abstraction; Tradier REST API is 3 endpoints |
| Tradier SDK | Direct requests | lumiwealth-tradier | Same reasoning; direct requests with typed response models is cleaner |
| Tastytrade SDK | tastyware/tastytrade | tastytrade-sdk (official) | Official SDK archived March 2026; community SDK is the maintained option |
| IV calculation | scipy.optimize.brentq | py_vollib LetsBeRational | LetsBeRational is faster but py_vollib is abandoned; scipy is reliable and already available |
| GEX computation | numpy (custom) | No alternative | No established GEX library exists; the math is simple enough for custom implementation |
## Installation
```bash
# Core options dependencies (new)
uv add blackscholes>=0.2.0 tastytrade>=12.3.1 matplotlib>=3.9.0
# Already present in project (no action needed)
# requests, pandas, numpy (indirect), scipy (indirect), pydantic (indirect)
```
**Environment variables to add to `.env.example`:**
```bash
# Options data providers
TRADIER_API_KEY=your_tradier_api_key # Get free sandbox key at developer.tradier.com
TRADIER_ENVIRONMENT=sandbox # "sandbox" or "production"
TASTYTRADE_USERNAME=your_tastytrade_user # Required for streaming Greeks
TASTYTRADE_PASSWORD=your_tastytrade_pass
```
## Architecture Integration Notes
1. **Tradier fits the existing vendor pattern.** Create `tradingagents/dataflows/tradier.py` alongside `y_finance.py` and `alpha_vantage.py`. Same interface contract: function takes ticker + params, returns pandas DataFrame.
2. **Tastytrade streaming is optional.** The batch analysis flow (`propagate()`) works fine with Tradier's hourly-refreshed Greeks. Tastytrade DXLink streaming is an enhancement for scenarios needing fresher data.
3. **blackscholes is computation-only.** No API calls, no state. Use it in agent tool functions to compute 2nd-order Greeks from Tradier's 1st-order data + underlying price.
4. **GEX and flow detection are pure pandas/numpy.** No external dependencies beyond what's already in the project. These are custom computations wrapped as agent tools.
## Sources
- [Tradier Options Chain API docs](https://docs.tradier.com/reference/brokerage-api-markets-get-options-chains) -- HIGH confidence, official docs
- [tastyware/tastytrade SDK](https://github.com/tastyware/tastytrade) -- HIGH confidence, actively maintained community SDK (v12.3.1, Mar 2026)
- [tastytrade-sdk-python archived](https://github.com/tastytrade/tastytrade-sdk-python) -- HIGH confidence, archived Mar 2026
- [blackscholes package](https://github.com/CarloLepelaars/blackscholes) -- HIGH confidence, v0.2.0 Dec 2024, supports 3rd-order Greeks
- [py_vollib on PyPI](https://pypi.org/project/py_vollib/) -- HIGH confidence, v1.0.1 last released 2017
- [QuantLib-Python v1.41](https://quantlib-python-docs.readthedocs.io/en/latest/termstructures/volatility.html) -- HIGH confidence, official docs
- [SpotGamma GEX methodology](https://spotgamma.com/gamma-exposure-gex/) -- MEDIUM confidence, proprietary methodology with published formulas
- [SVI vs SABR comparison (2025 thesis)](https://repositori.upf.edu/items/eceeb187-f169-483e-bf67-416fd9e00d70) -- MEDIUM confidence, academic source
- [SVI fitting with Python](https://tradingtechai.medium.com/python-volatility-surface-modeling-data-fetching-iv-calculation-svi-fitting-and-visualization-80be58328ac6) -- LOW confidence, blog post but methodology is standard
- [NumPy 2.4.x release](https://numpy.org/news/) -- HIGH confidence, official
- [SciPy 1.17.x release](https://docs.scipy.org/doc/scipy/release.html) -- HIGH confidence, official

View File

@ -0,0 +1,175 @@
# Project Research Summary
**Project:** TradingAgents Options Trading Module
**Domain:** Options analysis module for multi-agent LLM trading system
**Researched:** 2026-03-29
**Confidence:** HIGH
## Executive Summary
TradingAgents is extending its multi-agent stock analysis system to support options trading analysis. The approach follows an established pattern in the codebase: specialized LangGraph agents with focused roles, a vendor-routed data layer, and LLM-driven interpretation of pre-computed quantitative signals. The options module slots in as a parallel agent team alongside the stock analysis team, using Tradier's REST API as the primary data source for options chains, Greeks, and IV, supplemented by the community-maintained tastytrade SDK for real-time streaming when needed.
The recommended stack is deliberately minimal and coherent with existing dependencies. Tradier provides options chains with ORATS-sourced 1st-order Greeks via simple REST calls -- no SDK needed, `requests` is already a project dependency. The `blackscholes` library (actively maintained, v0.2.0 Dec 2024) computes 2nd/3rd-order Greeks that Tradier does not return. GEX and flow detection are custom numpy/pandas computations -- no dedicated library exists and the math is straightforward enough to implement directly. SVI volatility surface fitting uses scipy's optimization routines, already an indirect dependency. The only net-new dependencies are `blackscholes`, `tastytrade` (optional), and optionally `matplotlib` for visualization.
The principal risks are: (1) stale Greeks from Tradier's hourly ORATS refresh causing wrong delta-neutral recommendations; (2) SVI calibration failure on illiquid options producing garbage vol surfaces; (3) GEX sign convention bugs that completely invert market structure analysis; and (4) the LLM hallucinating non-existent option contract symbols. All four have clear, implementation-level mitigations documented in the pitfalls research.
## Key Findings
### Recommended Stack
The core data stack is two vendors: Tradier for REST-based chains, Greeks, and IV (direct `requests` calls, no SDK needed), and tastytrade community SDK for optional real-time streaming via DXLink WebSocket. Tradier's free sandbox makes development straightforward; production requires a brokerage account. The official tastytrade SDK was archived in March 2026, making the `tastyware/tastytrade` community SDK (v12.3.1, 95%+ test coverage, full Pydantic typing) the only viable maintained option. It requires Python >=3.11, so the project's `requires-python` should be bumped from `>=3.10` to `>=3.11`.
All quantitative computation uses libraries already present or easily added: `blackscholes` for 2nd/3rd-order Greeks, `scipy.optimize` for IV solving (Brent's method) and SVI calibration, `scipy.interpolate` for vol surface construction, `numpy` for vectorized GEX computation, and `pandas` for structured output. QuantLib and py_vollib are both explicitly not recommended -- the former is a 200MB over-engineered dependency, the latter is abandoned since 2017.
**Core technologies:**
- **Tradier REST API (requests)**: Options chain data, 1st-order Greeks, IV via ORATS -- free sandbox, fits existing vendor-routing pattern
- **tastyware/tastytrade SDK v12.3.1**: Real-time Greeks streaming via DXLink WebSocket -- only maintained tastytrade SDK after official SDK archived March 2026
- **blackscholes >=0.2.0**: 2nd/3rd-order Greeks (Charm, Vanna, Volga) -- actively maintained Dec 2024, lightweight, no C dependencies
- **scipy (optimize + interpolate)**: IV solving via Brent's method, SVI calibration, vol surface interpolation -- already an indirect dependency
- **numpy >=2.0.0**: Vectorized GEX computation across full options chains -- already an indirect dependency
- **pandas >=2.3.0**: Structured output for chains, GEX tables, flow signals -- core existing dependency
### Expected Features
**Must have (table stakes):**
- Options chain retrieval (strikes, expirations, bid/ask) -- foundation for all other analysis
- 1st-order Greeks display (Delta, Gamma, Theta, Vega) -- every options platform shows these; Tradier returns them via ORATS
- Implied volatility per contract (bid_iv, mid_iv, ask_iv) -- fundamental to options valuation
- IV Rank / IV Percentile -- core metric for sell-vs-buy-premium decisions; requires 52-week IV history
- Options strategy recommendation (verticals, iron condors, straddles) -- the core value proposition
- Max profit/loss and breakeven calculation -- users must understand risk before acting
- DTE-based filtering -- standard 30-60 DTE workflow for income strategies
- Probability of profit (PoP) estimation -- expected by tastytrade-style traders; approximated from delta
**Should have (competitive differentiators):**
- 2nd-order Greeks (Charm, Vanna, Volga) -- institutional-level insight not on retail platforms
- GEX analysis with Call/Put Walls and gamma flip zone -- SpotGamma equivalent ($199+/mo); free is high-value
- Volatility surface construction (SVI fitting) -- quantitative vol skew and term structure analysis
- TastyTrade methodology rules engine (IVR thresholds, 45 DTE entry, 21 DTE management, 50% profit targets)
- Unusual options activity detection -- smart money signal via volume/OI heuristics
- Multi-leg strategy construction with specific named contracts
- MenthorQ-style composite Options Score (0-5) -- single number summarizing the options environment
**Defer (v2+):**
- Real-time streaming dashboard -- batch `propagate()` flow does not support it architecturally
- 0DTE strategy analysis -- requires sub-second data; hourly Greeks are too stale
- Options backtesting engine -- separate domain requiring historical vol surfaces and fill simulation
- Portfolio-level Greeks aggregation -- requires position tracking; analysis-only scope has no position state
- Historical IV surface storage -- requires ORATS subscription or building own historical database
### Architecture Approach
The options module follows all three core patterns already established in the codebase: agent factory closures (each specialist agent created via a `create_*()` closure), vendor-routed data layer (new `get_options_chain()` function routes to Tradier or tastytrade based on config), and computation modules as pure stateless functions that take DataFrames and return DataFrames. The module hierarchy mirrors the existing stock analysis team: a parallel `options_team.py` LangGraph StateGraph with specialist agents consuming a shared options chain DataFrame fetched at the start of the pipeline.
The critical architectural rule from the research: **all math in Python, all interpretation by LLM.** The LLM must never be asked to calculate Greeks, GEX, or IV. A single wrong calculation cascades into bad strategy recommendations. Pre-compute everything numerically, then pass results to the agent for interpretation.
**Major components:**
1. `tradingagents/dataflows/tradier.py` -- Options chain retrieval, expirations, strikes via Tradier REST
2. `tradingagents/options/gex.py` -- GEX computation, Call/Put Walls, gamma flip zone (pure numpy functions)
3. `tradingagents/options/volatility.py` -- IV Rank/Percentile, SVI surface fitting, vol skew metrics
4. `tradingagents/options/greeks.py` -- 2nd/3rd order Greeks via blackscholes library
5. `tradingagents/options/flow.py` -- Volume/OI analysis, unusual activity heuristics
6. `tradingagents/options/strategies.py` -- Multi-leg construction, P/L profiles, PoP estimation
7. `tradingagents/options/scoring.py` -- MenthorQ-style composite Options Score (0-5)
8. `tradingagents/agents/options/` -- Agent factory functions for each options analyst role
9. `tradingagents/graph/options_team.py` -- LangGraph StateGraph composing the full options pipeline
### Critical Pitfalls
1. **Stale Greeks causing wrong directional recommendations** -- Always display the Greeks timestamp from Tradier response; warn in agent output if Greeks are >30 minutes old; compute IV from live bid/ask using scipy rather than relying solely on API-provided IV.
2. **SVI calibration failure on illiquid options** -- Filter strikes to minimum OI >100 and maximum bid-ask spread <30% of mid before calibrating; fall back to linear interpolation when fewer than 5 liquid strikes exist; apply Gatheral's no-butterfly-arbitrage constraints.
3. **GEX sign convention bugs inverting market structure analysis** -- Use a single canonical GEX function with comprehensive unit tests; add sanity check that net GEX is positive at/above spot and negative below for a typical equity.
4. **LLM hallucinating non-existent option contract symbols** -- Strategy agent must select only from contracts present in the actual chain DataFrame returned by Tradier; never let the LLM generate symbols from scratch.
5. **Python version incompatibility with tastytrade SDK** -- Bump `requires-python` to `>=3.11` when adding the options module; numpy/scipy latest versions also dropped 3.10 support.
## Implications for Roadmap
Based on research, suggested phase structure:
### Phase 1: Data Foundation and Core Analysis Pipeline
**Rationale:** Every feature depends on options chain data. Tradier integration is the prerequisite dependency for the entire module. GEX is the highest-value differentiator and is computationally simple (pure numpy arithmetic) once chain data flows -- there is no reason to defer it.
**Delivers:** Tradier data layer, IV Rank/Percentile, 1st-order Greeks display, GEX with Call/Put Walls and gamma flip zone, basic strategy recommendation agent with max P/L, breakeven, PoP.
**Addresses:** All table stakes features: chain retrieval, 1st-order Greeks, IV, IV Rank, DTE filtering, basic strategy recommendation, PoP estimation.
**Avoids:** GEX sign convention pitfall (unit tests required in this phase before LLM consumes GEX output); stale Greeks pitfall (timestamp display from day one).
### Phase 2: Advanced Analytics and Rules Engine
**Rationale:** With the data layer and basic analysis working, 2nd-order Greeks and the SVI vol surface add institutional depth. The TastyTrade rules engine requires IV Rank (Phase 1 output) as its primary input. Unusual flow detection is feasible with volume/OI heuristics despite Tradier's lack of trade-level data.
**Delivers:** 2nd/3rd-order Greeks (Charm, Vanna, Volga), volatility surface (SVI fitting), TastyTrade methodology rules engine with IVR thresholds and DTE management, unusual activity detection, specific multi-leg contract construction.
**Uses:** blackscholes >=0.2.0, scipy SVI calibration (SLSQP with no-arbitrage constraints), pandas flow heuristics.
**Implements:** `tradingagents/options/greeks.py`, `tradingagents/options/volatility.py`, `tradingagents/options/flow.py`.
**Avoids:** SVI calibration failure pitfall (liquidity filters and fallback to interpolation required here); IV Rank window ambiguity (explicit 252-day rolling definition in code and agent prompts).
### Phase 3: Composite Scoring, Debate, and Full Pipeline Integration
**Rationale:** The composite Options Score (0-5) and the Options Debate/Portfolio Manager require all analysis components as stable inputs. This phase assembles the full LangGraph StateGraph connecting all agents, adds the debate round, and produces the final portfolio manager recommendation with specific named contracts.
**Delivers:** MenthorQ-style composite Options Score synthesizing IV rank, GEX regime, flow signals, and vol skew; full Options Debate (bull vs bear on options thesis); Options Portfolio Manager producing final recommendations.
**Implements:** `tradingagents/options/scoring.py`, `tradingagents/agents/options/` full team, `tradingagents/graph/options_team.py` complete StateGraph.
### Phase 4: Streaming Enhancement and Multi-Ticker Scaling
**Rationale:** tastytrade DXLink streaming is an enhancement for sub-minute data freshness, not a core requirement for the batch `propagate()` flow. Multi-ticker support and Tradier rate limit management should only be tackled after the single-ticker pipeline is proven correct.
**Delivers:** tastytrade DXLink WebSocket integration, API rate limit management (exponential backoff, caching, 4-nearest-expirations optimization), multi-ticker batch analysis support.
**Avoids:** Premature optimization and synchronous WebSocket overhead pitfall (streaming only for persistent sessions, not per-call).
### Phase Ordering Rationale
- **Data before analysis:** Tradier integration is the prerequisite dependency for every other component. No agent can run without the chain DataFrame.
- **High-value, low-complexity first:** GEX computation is pure numpy arithmetic but delivers SpotGamma-level analysis ($199+/mo equivalent). Front-loading it in Phase 1 ensures differentiated value from the first working release.
- **SVI deferred to Phase 2:** SVI calibration has the highest implementation risk (convergence failures, illiquid edge cases). Deferring it avoids blocking the Phase 1 pipeline on the hardest numerical problem.
- **Composite scoring last among core features:** The Options Score is a synthesis of all other signals. Building it before the underlying signals are stable produces a meaningless number.
- **This ordering avoids the primary pitfalls:** GEX sign bugs are caught in Phase 1 unit tests before the LLM consumes the output; SVI failure modes are isolated to Phase 2 with explicit fallbacks; LLM contract hallucination is prevented in Phase 3 by constraining selection to the chain DataFrame.
### Research Flags
Phases likely needing deeper research during planning:
- **Phase 2 (SVI calibration):** The Gatheral no-butterfly-arbitrage constraint implementation is non-trivial. Needs deeper research into exact scipy SLSQP constraint formulation and parameter bounds before implementation begins.
- **Phase 2 (flow detection heuristics):** True sweep/block detection is not possible with Tradier's data. The exact volume/OI thresholds and their false-positive rates on real data need validation -- may require empirical tuning during implementation.
- **Phase 3 (options debate agent design):** The debate agent pattern exists for stock analysis but options-specific bull/bear framing (IV environment, not just price direction) is novel and will likely need prompt iteration.
Phases with standard patterns (skip research-phase):
- **Phase 1 (Tradier API integration):** REST API with official docs, straightforward vendor-pattern integration following existing `y_finance.py` and `alpha_vantage.py` models.
- **Phase 1 (GEX computation):** SpotGamma formula is published, numpy implementation is arithmetic, unit tests are sufficient validation.
- **Phase 2 (blackscholes integration):** Actively maintained library with clear API; standard function calls with no architectural complexity.
- **Phase 4 (LangGraph StateGraph):** Existing pattern in `tradingagents/graph/`; follow existing `trading_graph.py` structure.
## Confidence Assessment
| Area | Confidence | Notes |
|------|------------|-------|
| Stack | HIGH | Core recommendations (Tradier, blackscholes, scipy, numpy) verified against official docs and PyPI; tastytrade SDK archival confirmed; py_vollib abandonment confirmed with 2017 last release date |
| Features | HIGH | Feature set derived from established methodologies (SpotGamma, TastyTrade) with documented formulas; anti-features clearly scoped with rationale |
| Architecture | HIGH | Options module mirrors existing codebase patterns directly; LangGraph StateGraph pattern is well-established in the project |
| Pitfalls | MEDIUM | GEX sign convention and SVI failure modes are from documented technical sources; LLM hallucination risk is inferred from general LLM behavior; flow detection limitations are well-understood data availability constraints |
**Overall confidence:** HIGH
### Gaps to Address
- **Historical IV data endpoint:** IV Rank requires 52-week historical IV. Tradier provides historical options data but the exact endpoint and data quality for building a consistent IV history need validation before Phase 1 planning finalizes the approach. Fallback: compute historical IV from underlying historical price data using yfinance (already a dependency).
- **Tradier sandbox vs production fidelity:** The sandbox uses delayed/simulated data. ORATS Greeks quality differences between sandbox and production should be documented during Phase 1 implementation to prevent surprises at launch.
- **SVI no-arbitrage constraint implementation:** Gatheral's conditions are referenced but the exact scipy parameter bounds and constraint functions for SLSQP need to be worked out during Phase 2 planning -- this is a known implementation complexity, not a blocker.
- **Multi-expiration GEX weighting:** SpotGamma's exact weighting methodology across expirations is proprietary. The 4-nearest-expirations approach is documented; the optimal weighting scheme needs empirical validation during Phase 1.
- **Trade-level flow data:** Tradier does not provide individual fills or exchange sweep data. The "unusual activity detection" feature must be scoped as volume/OI heuristics and this limitation must be surfaced explicitly in agent output rather than marketed as sweep detection.
## Sources
### Primary (HIGH confidence)
- [Tradier Options Chain API docs](https://docs.tradier.com/reference/brokerage-api-markets-get-options-chains) -- chain endpoints, Greeks fields, rate limits
- [tastyware/tastytrade SDK v12.3.1](https://github.com/tastyware/tastytrade) -- DXLink streaming, Python version requirements, test coverage
- [tastytrade-sdk-python archived March 2026](https://github.com/tastytrade/tastytrade-sdk-python) -- archival confirmed
- [blackscholes v0.2.0](https://github.com/CarloLepelaars/blackscholes) -- Greek coverage, maintenance status, Python version support
- [py_vollib v1.0.1 on PyPI](https://pypi.org/project/py_vollib/) -- last released 2017, confirmed abandoned
- [NumPy 2.x release notes](https://numpy.org/news/) -- version compatibility
- [SciPy 1.14+ release notes](https://docs.scipy.org/doc/scipy/release.html) -- optimize and interpolate API
### Secondary (MEDIUM confidence)
- [SpotGamma GEX methodology](https://spotgamma.com/gamma-exposure-gex/) -- GEX formula, sign conventions, wall/flip zone definitions
- [Gatheral SVI arbitrage-free conditions](https://mfe.baruch.cuny.edu/wp-content/uploads/2013/01/OsakaSVI2012.pdf) -- SVI no-butterfly-arbitrage constraints
- [TastyTrade methodology](https://developer.tastytrade.com/) -- IVR thresholds, DTE management rules, PoP approximation from delta
- [SVI vs SABR comparison (2025 thesis, UPF)](https://repositori.upf.edu/items/eceeb187-f169-483e-bf67-416fd9e00d70) -- model choice rationale for equity options
- [Unusual options activity heuristics](https://intrinio.com/blog/how-to-read-unusual-options-activity-7-easy-steps) -- volume/OI ratio thresholds
### Tertiary (LOW confidence)
- [Python vol surface modeling blog post](https://tradingtechai.medium.com/python-volatility-surface-modeling-data-fetching-iv-calculation-svi-fitting-and-visualization-80be58328ac6) -- SVI fitting implementation example; methodology is standard even if source is a blog
---
*Research completed: 2026-03-29*
*Ready for roadmap: yes*