--- title: StratoTest emoji: ๐Ÿ“ˆ colorFrom: purple colorTo: pink sdk: docker app_port: 7860 pinned: true --- # StratoTest by Team Prahari ### Agentic AI Backtesting Tool โ€” Describe a strategy in plain English. Get a full backtest in seconds. [![Live Demo](https://img.shields.io/badge/๐Ÿค—%20Hugging%20Face-Live%20Demo-blue)](https://darshanpurohit-stratotest.hf.space/) [![Space](https://img.shields.io/badge/๐Ÿค—%20Hugging%20Face-Space%20+%20Code-yellow)](https://huggingface.co/spaces/Darshanpurohit/StratoTest/) [![FastAPI](https://img.shields.io/badge/Backend-FastAPI-009688)](https://fastapi.tiangolo.com/) [![Streamlit](https://img.shields.io/badge/Frontend-Streamlit-FF4B4B)](https://streamlit.io/) --- ---
# TEAM PRAHARI ``` โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ Built by three builders. โ•‘ โ•‘ Powered by one obsession. โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ```
|    ๐Ÿง‘โ€๐Ÿ’ป    | Builder |    GitHub    | |:---:|:---|:---:| | ![](https://img.shields.io/badge/-โ—-ff6b6b?style=flat-square) | **Chandan Singh** | [![GitHub](https://img.shields.io/badge/chandan22468-%23181717?style=for-the-badge&logo=github)](https://github.com/chandan22468) | | ![](https://img.shields.io/badge/-โ—-ffd93d?style=flat-square) | **Darshan Purohit** | [![GitHub](https://img.shields.io/badge/darshanpurohit20-%23181717?style=for-the-badge&logo=github)](https://github.com/darshanpurohit20) | | ![](https://img.shields.io/badge/-โ—-6bcb77?style=flat-square) | **Harsh Redasani** | [![GitHub](https://img.shields.io/badge/redasaniharsh-%23181717?style=for-the-badge&logo=github)](https://github.com/redasaniharsh) |
![](https://img.shields.io/badge/Hackathon-2026-blueviolet?style=for-the-badge) ![](https://img.shields.io/badge/Made%20with-Claude%20+%20Gemini%20+%20Pinecone-black?style=for-the-badge) ![](https://img.shields.io/badge/India-๐Ÿ‡ฎ๐Ÿ‡ณ-orange?style=for-the-badge)
--- ## ๐ŸŒ Deployed Links | Interface | URL | |---|---| | **Direct UI** | [darshanpurohit-stratotest.hf.space](https://darshanpurohit-stratotest.hf.space/) | | **UI + Codebase (Hugging Face Space)** | [huggingface.co/spaces/Darshanpurohit/StratoTest](https://huggingface.co/spaces/Darshanpurohit/StratoTest/) | --- ## ๐Ÿง  What is StratoTest? StratoTest is a **multi-agent AI backtesting system**. A user types a trading strategy in plain English. A pipeline of autonomous AI agents converts that description into executable Python code, validates it, runs a realistic historical simulation with friction modelling, generates a performance tearsheet, and then autonomously optimizes the strategy โ€” all without any further user input. A **Talkback Validation Agent** acts as a conversational gatekeeper, ensuring queries are complete before expensive computation begins. A **Pinecone RAG Layer** provides a strategy memory store, surfacing historically relevant configurations to auto-fill missing details and improve results over time. --- ## โœจ Key Features (USPs) 1. **Self-correcting code generation** โ€” The agent writes Python strategy code, runs it in a sandbox, and fixes its own errors without user intervention. Not a chatbot โ€” an agent with a goal. 2. **Autonomous optimization loop** โ€” The Optimization Agent tries parameter variants, compares results, keeps improvements, and discards regressions. Goal-driven: targets Sharpe > 1.0 and Max Drawdown < 20%. 3. **Lookahead bias detection** โ€” The Validation Agent checks for future data leakage, a real quantitative finance concern that most tools ignore entirely. 4. **Live agent reasoning panel** โ€” Every tool call, every decision, every fix is streamed to the UI in real time. Watch the agent think. 5. **Session memory** โ€” "Test the same strategy but add a volume filter" works because agents remember prior runs. 6. **Friction-realistic results** โ€” Slippage, commissions, and spread are baked in. Results reflect what you'd actually make, not theoretical maximums. 7. **Explain Agent** โ€” Post-backtest, ask "Why did it lose in 2022?" and get a narrative explanation with structural fix suggestions. 8. **Talkback Validation Layer** โ€” Before any compute, the Talkback Agent confirms all required fields (asset, timeframe, date range, strategy intent) โ€” using RAG to auto-suggest smart defaults from past successful runs. 9. **Pinecone RAG Memory** โ€” Every successful backtest is embedded and stored. Future queries retrieve semantically similar past configs to guide decisions automatically. --- ## ๐Ÿ—๏ธ System Architecture ### The Multi-Agent Pipeline ``` User Natural Language Input โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ TALKBACK AGENT (NEW) โ”‚ โ† Validates query completeness โ”‚ โ”‚ Uses Pinecone RAG for smart defaults โ”‚ Checks: โ”‚ Asks user only if RAG can't fill gaps โ”‚ โ€ข asset_name โ”‚ โ”‚ โ€ข timeframe โ”‚ โ”‚ โ€ข start_date / end_date โ”‚ โ”‚ โ€ข strategy_hint โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ enriched, complete query โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ STRATEGY AGENT โ”‚ โ† LangChain + Claude + Tools โ”‚ โ”‚ Writes Python strategy code โ”‚ Tools: โ”‚ Self-corrects syntax errors โ”‚ โ€ข validate_syntax โ”‚ Loops until sandbox passes โ”‚ โ€ข run_sandbox_test โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ validated strategy code (Python string) โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ VALIDATION AGENT โ”‚ โ† Separate LLM call โ”‚ โ”‚ Checks lookahead bias โ”‚ Checks: โ”‚ Minimum trade count โ”‚ โ€ข lookahead bias โ”‚ Sharpe sanity check โ”‚ โ€ข trade frequency โ”‚ Sends PASS or FAIL+reason โ”‚ โ€ข Sharpe sanity โ”‚ back to Strategy Agent โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ PASS โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ BACKTEST ENGINE โ”‚ โ† Pure Python, no LLM โ”‚ โ”‚ exec() the strategy code โ”‚ Applies: โ”‚ Apply friction costs โ”‚ โ€ข slippage โ”‚ Calculate all metrics โ”‚ โ€ข commissions โ”‚ โ”‚ โ€ข spread โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ metrics dict โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ OPTIMIZATION AGENT โ”‚ โ† LangChain + Claude + Tools โ”‚ โ”‚ Goal: Sharpe > 1.0, DD < 20% โ”‚ Tools: โ”‚ ONE tweak per iteration โ”‚ โ€ข tweak_parameter โ”‚ Max 4 iterations โ”‚ โ€ข run_full_backtes โ”‚ Returns best variant โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ best strategy + all iteration metrics โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ TEARSHEET + UI โ”‚ โ† Plotly charts + Streamlit โ”‚ โ”‚ Equity curve โ”‚ Shows: โ”‚ Drawdown chart โ”‚ โ€ข Original vs Best โ”‚ Monthly returns heatmap โ”‚ โ€ข Iteration table โ”‚ Agent reasoning log โ”‚ โ€ข Explain button โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ on-demand โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ EXPLAIN AGENT โ”‚ โ† Single LLM call, no tools โ”‚ โ”‚ Analyzes bad periods โ”‚ Answers: โ”‚ Explains WHY it lost money โ”‚ โ€ข "Why 2022 loss?" โ”‚ Suggests structural fixes โ”‚ โ€ข "What kills it?" โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` ### RAG + Talkback Layer (Intelligence Layers) The existing pipeline is extended with two intelligence layers that prevent silent hallucination and leverage historical strategy memory: ``` BEFORE (Old Flow): User Query โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Deep Agent โ†’ Backtest AFTER (New Flow): User Query โ†’ [Talkback Agent] โ†’ [RAG Layer] โ†’ [Validation Gate] โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ–ผ โ–ผ [Complete Query] [Incomplete Query] โ”‚ โ”‚ โ”‚ [Ask User + LLM Defaults] โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ–ผ Deep Agent Controller โ”‚ โ–ผ Backtest Engine โ”‚ โ–ผ [Index Result โ†’ Pinecone RAG] ``` | Layer | Name | Role | Technology | |---|---|---|---| | Layer 1 | **Pinecone RAG Layer** | Retrieves historically relevant strategy configs from a vector database | Pinecone + Gemini Embeddings | | Layer 2 | **Talkback Validation Agent** | Validates all required fields; uses RAG to suggest smart defaults; asks user only when necessary | Gemini 2.0 Flash + Pinecone | #### What Gets Stored in Pinecone Every successful backtest (win rate > 50%) is embedded and stored. Each vector carries rich metadata: ```json { "strategy_id": "uuid-v4", "asset_name": "RELIANCE.NS", "asset_label": "Reliance Industries", "timeframe": "1d", "start_date": "2022-01-01", "end_date": "2024-01-01", "duration_label": "2 years", "strategy_type": "EMA Cross", "indicators_used": ["EMA_20", "EMA_50", "ADX"], "win_rate": 62.5, "roi": 18.3, "market_regime": "trending", "trade_count": 45, "summary_text": "EMA 20/50 crossover on Reliance Industries daily chart over 2 years trending regime" } ``` #### Talkback Decision Logic The Talkback Agent enforces that all 5 required fields are resolved before passing the query to the Deep Agent: | Field | Example Values | Resolution Path | |---|---|---| | `asset_name` | `"Nifty 50"`, `"RELIANCE"`, `"BTC/USD"` | User text โ†’ NER โ†’ RAG suggestion โ†’ User confirm | | `timeframe` | `"1d"`, `"1h"`, `"15m"`, `"1w"` | User text โ†’ RAG suggestion โ†’ LLM default | | `start_date` | `"2022-01-01"` | User text โ†’ duration math โ†’ LLM default | | `end_date` | `"2024-12-31"` or `"today"` | Derived from start + duration | | `strategy_hint` | `"RSI overbought"`, `"EMA cross"`, `"breakout"` | User intent โ†’ RAG strategy_type โ†’ LLM inference | Auto-fill threshold: if RAG confidence score > 0.85, the field is filled automatically and the user is notified. Below 0.85, the field goes to the missing list and the Talkback UI presents options. --- ## ๐Ÿš€ Quick Start ### 1. Clone and set up ```bash git clone https://github.com/darshanpurohit20/Prahari_Stratotest cd Prahari_Stratotest cp .env.example .env ``` ### 2. Add your API keys Edit `.env`: ```env ANTHROPIC_API_KEY=your_anthropic_key_here PINECONE_API_KEY=your_pinecone_key_here GEMINI_API_KEY=your_gemini_key_here ``` Get your Anthropic key at: https://console.anthropic.com/ ### 3. Install dependencies ```bash pip install -r requirements.txt ``` ### 4. (Optional) Seed Pinecone with sample strategies ```bash python scripts/seed_pinecone.py ``` ### 5. Start the FastAPI backend ```bash python -m uvicorn main:app --reload --port 8000 ``` ### 6. Start the Streamlit frontend (new terminal) ```bash streamlit run frontend/app.py ``` ### 7. Open browser - **Frontend:** http://localhost:8501 - **API Docs:** http://localhost:8000/docs --- ## ๐Ÿ“ Project Structure ``` prahari/ โ”‚ โ”œโ”€โ”€ main.py โ† FastAPI app factory + uvicorn runner โ”œโ”€โ”€ requirements.txt โ† All pinned dependencies โ”œโ”€โ”€ .env.example โ† Template for secrets (never commit .env) โ”œโ”€โ”€ .gitignore โ”œโ”€โ”€ config.py โ† Central config (env vars, constants) โ”‚ โ”œโ”€โ”€ agent/ โ† All LLM agent logic โ”‚ โ”œโ”€โ”€ tools.py โ† @tool decorated LangChain tools โ”‚ โ”œโ”€โ”€ strategy_agent.py โ† Agent 1: code generation + self-correction โ”‚ โ”œโ”€โ”€ validation_agent.py โ† Agent 2: bias + sanity checks โ”‚ โ”œโ”€โ”€ optimization_agent.py โ† Agent 3: autonomous parameter tuning โ”‚ โ”œโ”€โ”€ explain_agent.py โ† Agent 4: narrative loss explanation โ”‚ โ”œโ”€โ”€ memory.py โ† Session context store โ”‚ โ”œโ”€โ”€ pipeline.py โ† Master orchestrator โ”‚ โ”œโ”€โ”€ parser.py โ† Claude LLM parser โ”‚ โ””โ”€โ”€ prompts.py โ† All system prompts (single source of truth) โ”‚ โ”œโ”€โ”€ rag/ โ† RAG + Talkback intelligence layers (NEW) โ”‚ โ”œโ”€โ”€ embedder.py โ† Gemini text-embedding-004 wrapper โ”‚ โ”œโ”€โ”€ indexer.py โ† Pinecone upsert + index_completed_strategy() โ”‚ โ”œโ”€โ”€ retriever.py โ† Pinecone query + top-K fetch โ”‚ โ”œโ”€โ”€ talkback_agent.py โ† Talkback Validation Agent (Gemini 2.0 Flash) โ”‚ โ”œโ”€โ”€ default_generator.py โ† LLM Default Generator + static fallbacks โ”‚ โ””โ”€โ”€ validator.py โ† Entity extraction + confidence scoring โ”‚ โ”œโ”€โ”€ engine/ โ† Pure Python backtesting (no LLM) โ”‚ โ”œโ”€โ”€ data.py โ† yfinance OHLCV fetcher + indicator calc โ”‚ โ”œโ”€โ”€ backtester.py โ† exec() engine + trade simulator โ”‚ โ”œโ”€โ”€ friction.py โ† Slippage, commission, spread models โ”‚ โ”œโ”€โ”€ tearsheet.py โ† Metrics computation + chart data โ”‚ โ””โ”€โ”€ strategies/ โ”‚ โ”œโ”€โ”€ base.py โ† BaseStrategy ABC โ€” every generated class inherits this โ”‚ โ”œโ”€โ”€ ma_crossover.py โ† Strategy 1: MA / EMA Crossover โ”‚ โ”œโ”€โ”€ rsi_reversal.py โ† Strategy 2: RSI Reversal โ”‚ โ”œโ”€โ”€ fibonacci_pullback.py โ† Strategy 3: Fibonacci Pullback โ”‚ โ””โ”€โ”€ strategies.py โ† Strategies 4โ€“10 โ”‚ โ”œโ”€โ”€ api/ โ† FastAPI REST layer โ”‚ โ”œโ”€โ”€ models/ โ”‚ โ”‚ โ”œโ”€โ”€ request.py โ† Pydantic input models โ”‚ โ”‚ โ””โ”€โ”€ response.py โ† Pydantic output models โ”‚ โ””โ”€โ”€ routes/ โ”‚ โ”œโ”€โ”€ backtest.py โ† POST /backtest โ”‚ โ”œโ”€โ”€ talkback.py โ† POST /talkback/validate, POST /talkback/confirm (NEW) โ”‚ โ”œโ”€โ”€ strategy.py โ† GET /strategies, POST /explain โ”‚ โ””โ”€โ”€ health.py โ† GET /health โ”‚ โ”œโ”€โ”€ scripts/ โ”‚ โ””โ”€โ”€ seed_pinecone.py โ† One-time Pinecone seed script for testing โ”‚ โ””โ”€โ”€ frontend/ โ””โ”€โ”€ app.py โ† Streamlit UI (single file) ``` --- ## ๐ŸŽฏ Supported Strategies ### Classic | # | Strategy | |---|---| | 1 | MA / EMA Crossover | | 2 | RSI Reversal | | 3 | Fibonacci Pullback | | 4 | Support / Resistance Bounce | | 5 | Breakout + Retest | | 6 | Higher High Higher Low | ### SMC (Smart Money Concepts) | # | Strategy | |---|---| | 7 | Order Block Entry | | 8 | Fair Value Gap (FVG) | | 9 | Change of Character (CHoCH) | | 10 | Break of Structure + Pullback | --- ## ๐Ÿ’ฌ Example Inputs ``` "Buy when 50 EMA crosses above 200 EMA, SL below last swing low, 1:2 RR" "Buy at bullish order block, SL below OB, 1:3 RR" "Buy when RSI drops below 30, SL below swing low, 1:2 RR" "Buy at 0.618 fibonacci level in uptrend, 1:2 RR" "Buy after break of structure pullback, SL below BOS, 1:3 RR" "Buy when MACD crosses above signal line and RSI is below 60" "Buy at Bollinger Band lower band, sell at upper band" ``` --- ## ๐ŸŒ Supported Markets & Tickers | Market | Example Tickers | |---|---| | NSE India | `RELIANCE.NS`, `TCS.NS`, `INFY.NS` | | BSE India | `RELIANCE.BO` | | Nifty Index | `^NSEI`, `^NSEBANK` | | US Stocks | `AAPL`, `TSLA`, `GOOGL` | | Crypto | `BTC-USD`, `ETH-USD` | | Forex | `EURUSD=X`, `GBPUSD=X` | --- ## ๐Ÿ”Œ API Reference ### Core Endpoints | Method | Route | Description | |---|---|---| | `POST` | `/backtest` | Run a full agentic backtest | | `GET` | `/strategies` | List all supported strategy types | | `POST` | `/explain` | Ask the Explain Agent about backtest results | | `GET` | `/health` | Service health check | ### Talkback Endpoints (RAG Layer) | Method | Route | Description | |---|---|---| | `POST` | `/talkback/validate` | Submit a raw query for entity extraction + RAG validation | | `POST` | `/talkback/confirm` | Submit confirmed/modified fields to get an enriched query ready for the Deep Agent | #### Example: Validate a query ```bash curl -X POST http://localhost:8000/talkback/validate \ -H "Content-Type: application/json" \ -d '{"user_query": "RSI strategy on Nifty"}' ``` Response when fields are missing: ```json { "status": "incomplete", "resolved_fields": { "asset_name": "^NSEI", "strategy_hint": "RSI" }, "missing_fields": [ { "field": "timeframe", "question": "What timeframe should the backtest use?", "options": [ {"label": "Daily (1d)", "value": "1d"}, {"label": "Hourly (1h)", "value": "1h"}, {"label": "Weekly (1wk)", "value": "1wk"}, {"label": "Custom โ€” I'll type it", "value": null} ], "rag_suggestion": { "label": "Daily (based on similar Nifty RSI strategies)", "confidence": 0.91 } } ] } ``` --- ## ๐Ÿ“Š Data Schemas ### BacktestResult ```python { "total_trades": int, "sharpe_ratio": float, # annualised "max_drawdown_pct": float, # negative, e.g. -18.3 "win_rate_pct": float, # 0โ€“100 "total_return_pct": float, "profit_factor": float, "avg_trade_return_pct": float, "best_trade_pct": float, "worst_trade_pct": float, "equity_curve": list[float], # one per bar "monthly_returns": dict[str, float], # {"2023-01": 2.3, ...} "warning": str | None, "error": str | None, "traceback": str | None, } ``` ### PipelineResult ```python { "success": bool, "strategy_name": str, "run_id": str, "strategy_code": str, "baseline_metrics": BacktestResult, "optimized_metrics": BacktestResult, "all_iterations": list[{ "label": str, "metrics": BacktestResult, "change_description": str, }], "improvement_pct": float, "goal_met": bool, "validation_issues": list[str], "reasoning_log": list[str], "stage_failed": str | None, "error": str | None, } ``` --- ## โš ๏ธ Error Handling Every agent function returns a result dict with a `"success"` or `"error"` key โ€” nothing raises unhandled exceptions. Errors are surfaced to the UI gracefully with friendly messages. | Stage | Fallback | |---|---| | Data fetch failure | Return early: `"Could not fetch data for {ticker}"` | | Strategy Agent fails | Return agent's last error + reasoning log | | Validation fails | Log warning, continue (sandbox already passed) | | Backtest fails | Return engine error + strategy code for debug | | Optimization fails | Return baseline results + log that optimization failed | | Pinecone unavailable | Skip RAG entirely, proceed with entity extraction only | | Gemini embedding fails | Use cached zero-vector, skip RAG for this request | | Pinecone upsert fails | Log warning, return backtest result normally โ€” non-blocking | | RAG returns 0 matches | Skip RAG suggestions, rely purely on LLM defaults | --- ## โž• Extending the System The system is designed so new features can be added without modifying existing files. ### Adding a New Strategy 1. Create `engine/strategies/my_strategy.py` 2. Inherit `BaseStrategy` 3. Implement `generate_signals()` and `get_indicators()` 4. Add to `STRATEGY_MAP` in `engine/backtester.py` 5. Add to `GET /strategies` in `api/routes/strategy.py` ### Adding a New Agent 1. Create `agent/new_agent.py` 2. Follow the pattern: `run_new_agent(inputs..., progress_callback) -> dict` 3. Add it as a step in `agent/pipeline.py` 4. Add its system prompt to `agent/prompts.py` ### Adding a New Chart 1. Add `build_X_chart(result: dict) -> go.Figure` to `engine/tearsheet.py` 2. Import and call it in `frontend/app.py` ### Adding Persistence (Redis/DB) 1. Modify `agent/memory.py` โ€” implement `save_session` and `get_or_create_session` to use Redis instead of the in-memory `_sessions` dict 2. No other files need to change ### Adding a New Market/Ticker Type 1. Nothing to change โ€” yfinance handles NSE (`.NS`), crypto (`-USD`), and forex (`=X`) automatically 2. Optionally add examples to the UI pill buttons in `frontend/app.py` --- ## ๐Ÿงช Testing ### Unit Tests ```bash # Run all tests pytest tests/ # Key test cases # tests/test_talkback.py ``` ```python def test_complete_query_returns_ready(): result = process_query("Backtest Nifty 50 EMA crossover daily from 2022 to 2024") assert result["status"] == "ready" assert result["enriched_query"]["asset_name"] == "^NSEI" def test_missing_timeframe_triggers_talkback(): result = process_query("RSI strategy on Reliance from 2022") assert result["status"] in ["incomplete", "ready"] if result["status"] == "incomplete": assert "timeframe" in result["talkback_options"] def test_completely_vague_query_returns_all_missing(): result = process_query("run a backtest") assert result["status"] == "incomplete" assert len(result["talkback_options"]) >= 3 ``` ### Integration Test (End-to-End) ```bash # Start the backend uvicorn api.main:app --reload # Test talkback route curl -X POST http://localhost:8000/talkback/validate \ -H "Content-Type: application/json" \ -d '{"user_query": "RSI strategy on Nifty"}' # Test engine in isolation (no API key needed) python -c " from engine.data import fetch_ohlc from engine.backtester import run_backtest_from_code df = fetch_ohlc('AAPL', '90d') print(df.columns.tolist()) print(f'Data shape: {df.shape}') " ``` ### Seed Pinecone for RAG Testing ```bash python scripts/seed_pinecone.py ``` --- ## ๐Ÿ”ง Environment Variables ```env # Required ANTHROPIC_API_KEY=sk-ant-... PINECONE_API_KEY=... GEMINI_API_KEY=... # Optional (with defaults) DEFAULT_TICKER=AAPL DEFAULT_PERIOD=2y MAX_OPTIMIZATION_ITERATIONS=4 SANDBOX_TEST_DAYS=90 MIN_TRADES_FOR_VALID_STRATEGY=3 COMMISSION_PCT=0.001 SLIPPAGE_PCT=0.0005 RAG_AUTO_FILL_THRESHOLD=0.85 RAG_TOP_K=5 ``` --- *Team Prahari | Hackathon 2026*