Spaces:
Sleeping
Download README.md from Darshanpurohit/StratoTest: direct link, hf CLI and curl.
- Browser
- Download file 24.9 kB
-
https://huggingface.co/spaces/Darshanpurohit/StratoTest/resolve/main/README.md
- Command line
-
hf download hf://spaces/Darshanpurohit/StratoTest/README.md
-
curl -L -o README.md https://huggingface.co/spaces/Darshanpurohit/StratoTest/resolve/main/README.md
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.
TEAM PRAHARI
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Built by three builders. β
β Powered by one obsession. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Deployed Links
| Interface | URL |
|---|---|
| Direct UI | darshanpurohit-stratotest.hf.space |
| UI + Codebase (Hugging Face Space) | 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)
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.
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%.
Lookahead bias detection β The Validation Agent checks for future data leakage, a real quantitative finance concern that most tools ignore entirely.
Live agent reasoning panel β Every tool call, every decision, every fix is streamed to the UI in real time. Watch the agent think.
Session memory β "Test the same strategy but add a volume filter" works because agents remember prior runs.
Friction-realistic results β Slippage, commissions, and spread are baked in. Results reflect what you'd actually make, not theoretical maximums.
Explain Agent β Post-backtest, ask "Why did it lose in 2022?" and get a narrative explanation with structural fix suggestions.
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.
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:
{
"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
git clone https://github.com/darshanpurohit20/Prahari_Stratotest
cd Prahari_Stratotest
cp .env.example .env
2. Add your API keys
Edit .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
pip install -r requirements.txt
4. (Optional) Seed Pinecone with sample strategies
python scripts/seed_pinecone.py
5. Start the FastAPI backend
python -m uvicorn main:app --reload --port 8000
6. Start the Streamlit frontend (new terminal)
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
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:
{
"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
{
"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
{
"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
- Create
engine/strategies/my_strategy.py - Inherit
BaseStrategy - Implement
generate_signals()andget_indicators() - Add to
STRATEGY_MAPinengine/backtester.py - Add to
GET /strategiesinapi/routes/strategy.py
Adding a New Agent
- Create
agent/new_agent.py - Follow the pattern:
run_new_agent(inputs..., progress_callback) -> dict - Add it as a step in
agent/pipeline.py - Add its system prompt to
agent/prompts.py
Adding a New Chart
- Add
build_X_chart(result: dict) -> go.Figuretoengine/tearsheet.py - Import and call it in
frontend/app.py
Adding Persistence (Redis/DB)
- Modify
agent/memory.pyβ implementsave_sessionandget_or_create_sessionto use Redis instead of the in-memory_sessionsdict - No other files need to change
Adding a New Market/Ticker Type
- Nothing to change β yfinance handles NSE (
.NS), crypto (-USD), and forex (=X) automatically - Optionally add examples to the UI pill buttons in
frontend/app.py
π§ͺ Testing
Unit Tests
# Run all tests
pytest tests/
# Key test cases
# tests/test_talkback.py
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)
# 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
python scripts/seed_pinecone.py
π§ Environment Variables
# 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