Agentic Options Strategy Project
Introduction
Agentic Options Strategy Project

Introduction
The financial markets, and options trading in particular, have long been dominated by complexity — not just in execution, but in the very process of forming a strategy. A trader looking to express a market view must simultaneously reason about strike selection, expiry choice, implied volatility environment, multi-leg payoff structures, margin requirements, and four interacting Greeks. Even experienced practitioners rely on intuition and hard-won pattern recognition to navigate this space. For most, the gap between having a market view and translating that view into a properly structured, risk-calibrated trade remains significant.
The Agentic Options Strategy Platform is built to close that gap.
This platform represents a new class of financial tooling — one where artificial intelligence does not merely display data or run pre-programmed screens, but actively reasons alongside the trader. A user describes their intent in plain English: “I want a neutral strategy on SPY with a max loss of five hundred dollars, expiring in about thirty days.” The system takes that intent, searches its memory of historical strategy patterns, drafts a multi-leg options strategy calibrated to current market conditions, validates it against hard risk constraints, and subjects it to a final judgment before surfacing it as an executable trade recommendation — complete with a payoff diagram, live Greeks, and a step-by-step order plan.
This is made possible by a layered architecture that brings together several of the most significant advances in applied AI engineering. LangGraph provides the orchestration backbone — a stateful, directed graph that models the strategy generation process as a sequence of discrete reasoning steps, each with typed inputs and outputs, and the ability to loop back and self-correct when constraints are violated.
CrewAI wraps the platform’s domain capabilities — market data retrieval, risk analysis, Greeks computation, execution planning — into composable, reusable agent tools.
ChromaDB grounds the AI’s reasoning in institutional memory, preventing hallucination by anchoring every generated strategy in semantically similar historical precedents.
Anthropic’s Claude provides the natural language understanding that makes the entire interface conversational.
FastAPI and Streamlit form the backend and frontend respectively, chosen for their Python-native simplicity and suitability for quantitative workflows. And underneath it all, a production infrastructure stack — PostgreSQL with TimescaleDB, Redis, Celery, Prometheus, Grafana, Nginx, and Docker Compose — handles persistence, background processing, observability, and deployment.
The platform is structured around four user-facing experiences. The Strategy Lab provides a direct, visual interface for traders who know exactly what they want to build and need fast feedback on payoff shape and Greeks. The Natural Language Builder is the AI-native entry point, where market intent becomes a structured strategy through the full agentic pipeline. The Execute Trade page enforces deliberate, risk-acknowledged execution with live Greeks recalculation and explicit order sequencing. The Agent Pipeline page makes the AI’s reasoning fully transparent — every node, every state transition, every validation error, every piece of Claude’s reasoning is surfaced and inspectable.
This document covers the platform’s architecture in depth: the rationale behind each technology choice, the end-to-end data flows that connect natural language to executed orders, the production readiness gaps that must be addressed before live capital deployment, and the evolution path toward a more capable, event-driven, self-improving system. It is written for ML and AI engineers who will build on, extend, or deploy this platform, as well as for technical stakeholders who need to understand the system’s design decisions and their trade-offs.
The architecture described here is not specific to options trading. The core pattern — a RAG-augmented agentic pipeline with tool-wrapped domain logic, an execution abstraction layer, and a full async worker and observability stack — is a general-purpose blueprint for AI-native applications in any domain where human expert workflows can be expressed as multi-step reasoning over a document or pattern store. Options trading is the first instantiation. The pattern itself is reusable wherever intelligent, accountable, real-time decision support is needed.
Flow Diagram

SECTION 1 — SYSTEM PURPOSE & ARCHITECTURE PHILOSOPHY
The platform is an AI-orchestrated options trading system. Unlike conventional dashboards, it uses autonomous agents to reason about market conditions, retrieve historical strategy patterns, validate risk parameters, and generate executable options strategies — driven entirely by natural language input.
1.1 The 9-Layer Architecture Model
Communication is strictly top-down — the UI never calls the quant engine directly, and the quant engine never touches the AI layer.


Key design principle: Layers communicate strictly downward. Any layer can be upgraded, replaced, or scaled without cascading changes to adjacent layers.
SECTION 2 — LAYER-BY-LAYER DESIGN RATIONALE
2.1 L1 — Streamlit Frontend
Streamlit is chosen over React/Vue because primary users are quant traders and ML engineers who write Python across the full stack. The Python-native paradigm eliminates context-switching between languages.

Trade-off: Streamlit is single-process. For 10+ concurrent users doing heavy computation, sessions compete for GIL-limited threads. Mitigation: offload all computation to FastAPI/Celery. Keep Streamlit as a thin display-only layer.
2.2 L2 — FastAPI Backend
Selected for async-native request handling (critical for I/O-bound market data calls), automatic OpenAPI documentation generation, and Pydantic-based validation that prevents malformed strategy data from reaching execution.

Why async: Options chain data from Polygon can involve 500+ strike records per symbol. Fetching multiple symbols concurrently with asyncio cuts latency from O(n × latency) to O(max_latency) — a 5–10× improvement on market data assembly.
2.3 L3 — LangGraph AI Orchestration
LangGraph implements the AI pipeline as a directed graph of nodes. The graph model enables conditional branching — the JUDGE node can route back to DRAFT if risk limits are violated, creating a self-correcting loop without restarting the full pipeline.

# LangGraph conditional routing — JUDGE node
def judge_router(state: PipelineState) -> str:
if state.risk_score > RISK_THRESHOLD:
return "draft" # loop back — re-draft with constraints
if state.execution_eligible:
return "end" # strategy approved
return "reject" # terminal rejection
Key insight: LangGraph’s explicit state machine prevents “reasoning collapse” — a failure mode in simple LLM chains where later steps forget earlier constraints. Every node receives the complete accumulated state, not just the previous node’s output.
2.4 L4 — CrewAI Tool Wrappers
Tools are stateless, typed, and independently testable. The wrapper pattern means the same tools can be reused by future autonomous agents (e.g., an overnight position monitor) without duplicating logic.

2.5 L5 — RAG Layer (ChromaDB)
ChromaDB stores embeddings of historical strategy patterns. RAG prevents two critical LLM failure modes: (1) hallucinating strategies that violate options mechanics, and (2) over-fitting to training data distribution rather than the firm’s documented history.
# ChromaDB strategy retrieval with metadata filter
collection = client.get_collection('strategy_patterns')
results = collection.query(
query_embeddings=[embed(user_intent)],
n_results=5,
where={'market_regime': current_regime} # pre-filter by IV environment
)
Production note: ChromaDB embedded mode is fine for development. In production it must run as a separate service, or be replaced with Weaviate/Qdrant for multi-tenant isolation, horizontal scaling, and persistent backup guarantees.
2.6 L6 — LLM Layer (Anthropic + Heuristic Fallback)
A heuristic fallback activates when the API is unavailable, rate-limited, or returns malformed output. The fallback uses rule-based strategy selection keyed on market regime signals. LLM API outages must not cause trading system downtime.

2.7 L7 — Quant / Pricing Engine
Pure Python (numpy/scipy) with zero ML dependencies. Handles payoff calculation across the underlying price range at expiry, Black-Scholes Greeks per leg and portfolio aggregate, risk metrics (max profit, max loss, breakevens, probability of profit), and CBOE/FINRA margin estimation.
# Portfolio Greeks aggregation across legs
def portfolio_greeks(legs: list[StrategyLeg]) -> Greeks:
delta = sum(bs_delta(l) * l.qty * l.direction for l in legs)
gamma = sum(bs_gamma(l) * l.qty for l in legs)
theta = sum(bs_theta(l) * l.qty * l.direction for l in legs)
vega = sum(bs_vega(l) * l.qty for l in legs)
return Greeks(delta=delta, gamma=gamma, theta=theta, vega=vega)
Design intent: The quant engine is intentionally dependency-free from AI frameworks. This ensures pricing logic is deterministic, fully testable with Pytest, and performant without GPU or model-loading overhead.
2.8 L8 — Execution Layer
The Adapter pattern: a base class defines the interface; concrete adapters fulfill it. Adding a live broker requires only implementing the base interface — no changes to AI, validation, or UI layers.

2.9 L9 — Data & Persistence
Three sub-systems: market data adapters (yfinance for dev, Polygon for production), PostgreSQL/TimescaleDB for relational + time-series data, and Redis for both application cache (TTL 30–60s) and Celery message broker.

SECTION 3 — END-TO-END DATA FLOWS
Flow A — Natural Language Strategy Generation
- User enters: “Neutral strategy on SPY, max loss $500, 30 days” in NL Builder page
- Streamlit POST → FastAPI /ai/generate-strategy
{ nl_text, ticker, constraints } - FastAPI calls
graph.invoke()— LangGraph begins pipeline with initial state - RETRIEVE: StrategyRetrievalTool embeds intent, queries ChromaDB → 5 similar historical patterns
- RETRIEVE: MarketContextTool fetches live IV rank, P/C ratio for SPY
- DRAFT: Claude receives NL intent + patterns + market context → returns StrategySpec JSON
- VALIDATE: RiskAnalysisTool checks max loss ≤ $500, margin within bounds
- VALIDATE: GreeksCalculatorTool checks portfolio Delta neutral within threshold
- JUDGE: risk_score evaluated — if passes → APPROVED; if max_loss exceeded → REVISE (loop to DRAFT with constraint hint)
- FastAPI returns
{ strategy, greeks, recommendation, execution_eligible }to Streamlit - NL Builder renders payoff diagram (via /strategy/payoff) and Greeks table
Flow B — Trade Execution
- User reviews strategy on Execute Trade page, checks risk disclosure, clicks Submit
- Streamlit POST → FastAPI /execution/submit
{ strategy_id, mode: 'paper' | 'live' } - ExecutionPlanTool sequences legs (sell legs first for margin efficiency), sets limit prices
- PaperAdapter receives leg order batch, simulates fills at mid-price
- Orders and fills persisted to PostgreSQL orders + fills tables with timestamp
- Celery beat schedules
refresh_greekstask for new position — fires every 5 minutes - Prometheus metrics updated:
active_positions_count,portfolio_delta,open_pnl
Flow C — Background Monitoring (Celery Beat)
- Celery beat fires
refresh_greekstask every 5 minutes for all active positions - Worker fetches current underlying prices and IV surface from Polygon/yfinance
- Quant engine recomputes portfolio Greeks for each active position
- Updated Greeks stored in TimescaleDB hypertable with UTC timestamp
- Prometheus scrapes /monitoring/metrics every 15 seconds
- Grafana dashboards display live Delta drift, Theta decay, Vega exposure over time
- Alert rules fire if portfolio Delta exceeds configured bound → notification to trader
SECTION 6 — RECOMMENDED ENHANCEMENTS
6.1 Event-Driven Architecture (Kafka / Kinesis)
Replace the 5-minute Celery cron with a real-time event bus. Market data updates publish to a market-data topic; Greeks recalculation triggers on each tick rather than on schedule.
Current (Celery cron)Event-Driven (Kafka)Greeks refreshed every 5 minutesGreeks refreshed on every market data tickFrontend polls for updatesFrontend receives P&L via WebSocket / server-sent eventsSingle Celery beat process is SPOFKafka consumer group scales horizontally, no SPOFLatency: up to 5 minutesLatency: sub-second after market data arrival
6.2 Self-Evaluation Agent Loop
Add a fifth LangGraph node: EVALUATE. After a strategy executes in paper mode, EVALUATE (triggered 7 days later by Celery beat) analyzes actual vs. predicted performance, updates ChromaDB embeddings with outcome data, and adjusts strategy confidence scores. Creates a self-improving RAG system that learns from its own paper-trading results.
6.3 Parallel Multi-Agent Strategy Generation
Run BullishAgent, BearishAgent, and NeutralAgent simultaneously via LangGraph branching. A meta-judge selects the best strategy given current market conditions. Reduces wall-clock latency and provides strategy diversity for the trader to choose from.
6.4 React / Next.js Frontend Migration
For production scale, replace Streamlit with React (Next.js) + FastAPI WebSocket support for real-time Greeks streaming, server-sent events for agent pipeline status, and a proper component library for financial UI. Decouples frontend deployment from backend and enables CDN distribution.
6.5 Backtesting Integration
Add a backtesting service using vectorbt or QuantLib. Users submit an AI-generated strategy for historical backtesting before paper trading. Results feed back into ChromaDB as additional outcome evidence, improving retrieval quality over time.


7.1 Industry Use Cases for This Architecture Pattern
The core pattern — RAG-augmented agentic pipeline with tool-wrapped domain logic, execution abstraction, and async worker infrastructure — is domain-agnostic.


Thank you for diving into this post. I hope this content helps in better understanding. If the content helped you, your claps and a follow on Medium would mean a lot — they help this knowledge reach more readers and keep me motivated to write more. Really appreciate your time and support!!!
메타데이터
- post_id
- 7c6ec2a0adb4
- slug
- agentic-options-strategy-project-7c6ec2a0adb4
- url
- https://blog.gopenai.com/agentic-options-strategy-project-7c6ec2a0adb4
- canonical_url
- https://blog.gopenai.com/agentic-options-strategy-project-7c6ec2a0adb4
- author_url
- https://medium.com/@rashmi18patel
- status
- ok
- fetched_at
- 2026-06-16 19:09:56