Documentation
Complete guide to the AI Hedge Fund trading platform — theory, strategies, and implementation
# Quick Start
Configure API Keys
Set up Upstox API credentials and Bedrock model ARNs. Saved model ARNs are hidden after save for security.
Authorize Broker
Complete OAuth flow to connect your trading account for live data
Generate Signals
Run the 11-Factor engine to scan F&O stocks and generate trading signals
System Architecture
The AI Hedge Fund is built on a multi-agent architecture where specialized AI agents collaborate to make investment decisions. The system combines:
- Quantitative Analysis — 11-Factor scoring engine for systematic stock screening
- Qualitative Analysis — LLM-powered news sentiment and event impact assessment
- Adversarial Debate — Bull/Bear agents argue positions with a Skeptic judge
- Risk Management — L1-L10 controls validate every trade before execution
- Options Intelligence — Greeks-based strategy selection and position sizing
Settings Security
Sensitive values in Settings are not all displayed the same way after save. Upstox and API secrets are masked, while saved Bedrock model ARNs are hidden entirely and replaced with a configured state.
For Primary Model and Fast Model, the input field appears only when no value is configured or when you click Change. This prevents long inference profile ARNs from being exposed in the UI while still allowing updates.
# 11-Factor Scoring Engine
Philosophy: Confluence of Factors
Markets are driven by multiple forces simultaneously. A stock might have strong momentum but weak structure, or excellent fundamentals but poor sentiment. The 11-Factor engine does not look for perfection in any single metric — it looks for confluence, where multiple independent factors align to create high-probability setups.
Each factor scores from -1.5 to +1.5, giving a total range of -16.5 to +16.5. We require |score| ≥ 7.5 for trades, meaning at least 5 factors must strongly align.
Seasonality
Historical monthly and weekly return patterns • Weight: 1.5
Markets exhibit recurring patterns. January Effect, month-end rebalancing, and weekly patterns (Monday weakness, Friday strength) create exploitable edges. We analyze 5 years of data to identify statistically significant seasonal patterns for each stock.
Trend
EMA alignment and slope analysis • Weight: 1.5
Trend is the most reliable edge in markets. We use the 20/50/200 EMA stack to identify trend direction and strength. When EMAs are properly aligned (20 > 50 > 200 for uptrend), the probability of continuation is significantly higher than reversal.
RSI Regime
Relative Strength Index with divergence detection • Weight: 1.0
RSI measures momentum velocity. Contrary to popular belief, overbought (>70) in uptrends often leads to MORE gains, not reversals. We look for RSI divergences (price makes new high, RSI doesn't) as warning signs, and RSI holding above 50 in uptrends as confirmation.
Structure
Support/Resistance and breakout analysis • Weight: 1.5
Price remembers levels. Previous highs become resistance, previous lows become support. Breakouts from consolidation ranges, especially on volume, indicate institutional commitment. We identify key levels using swing highs/lows and volume profile.
Volume
Volume expansion and accumulation/distribution • Weight: 1.5
Volume precedes price. Institutional accumulation shows up as rising price on rising volume. Distribution shows as rising price on declining volume (weak hands buying from smart money). We use OBV (On-Balance Volume) and volume ratio analysis.
Momentum
MACD, ADX, and Rate of Change • Weight: 1.0
Momentum measures the speed of price change. MACD crossovers identify momentum shifts, while ADX measures trend strength (>25 = strong trend). We combine multiple momentum indicators to filter false signals.
Volatility
ATR regime and Bollinger Band analysis • Weight: 1.0
Volatility is mean-reverting. Low volatility periods (tight Bollinger Bands) precede explosive moves. High volatility periods eventually contract. We measure ATR relative to its 50-day average to identify regime.
Relative Strength
Performance vs Nifty 50 benchmark • Weight: 1.5
In bull markets, buy the leaders. In bear markets, short the laggards. Stocks that outperform the index during market rallies tend to continue outperforming. We calculate rolling 20-day relative performance.
Price Action
Candlestick patterns and market structure • Weight: 1.0
Price action reflects market psychology. Patterns like hammer, engulfing, and doji at key levels signal potential reversals. We scan for high-probability patterns at support/resistance zones.
FII/DII Flow
Institutional money flow analysis • Weight: 1.5
Follow the smart money. FII (Foreign Institutional Investors) flows drive major trends in Indian markets. When FIIs are buying while DIIs (Domestic) are selling, it often indicates informed accumulation.
Options Flow
PCR, OI buildup, and Max Pain analysis • Weight: 1.5
Options market reveals institutional positioning. Put-Call Ratio > 1 indicates hedging/bearishness. OI buildup at strikes shows where big players expect price to go. Max Pain is where option writers profit most.
Score Interpretation
+7.5 to +15
Strong Buy — High conviction long
+4 to +7.5
Moderate Buy — Wait for better entry
-4 to -7.5
Moderate Sell — Wait for confirmation
-7.5 to -15
Strong Sell — High conviction short
# SEPA Stage Analysis
Minervini's 4 Market Stages
Every stock cycles through 4 stages. Stage identification is the most powerful filter in SEPA — it eliminates 70%+ of stocks immediately. Only Stage 2 stocks are eligible for long entries.
Stage is determined by two inputs: price vs SMA200 and SMA200 slope. All four stages eventually transition back to Stage 1 — the cycle repeats continuously.
Basing / Neglect
Watch — do not buy yet
Criteria
- • Price sideways, no clear trend
- • SMA200 flat (slope within ±1%)
- • Price may be above or below SMA200
- • Low volume, low analyst interest
After a prolonged decline, sellers are exhausted and price stabilizes. Smart money quietly accumulates while retail ignores the stock. This is the setup phase — no edge yet, but the next stage will be Stage 2.
Example
Stock has been flat for 6-18 months, SMA200 has stopped declining and flattened.
Advancing / Markup
BUY — only valid entry stage
Criteria
- • Price > SMA200 (above the line)
- • SMA200 slope rising > 0.5% over 20 days
- • Ideal: SMA50 > SMA150 > SMA200 (stacked)
- • Price making higher highs and higher lows
Institutions are buying aggressively. Price breaks above SMA200 and the moving average itself starts rising — confirming the trend. VCP patterns form here as the stock consolidates between breakouts. This is the only stage where odds favor longs.
Example
Typical example: a stock clears SMA200 on strong volume, moving averages stack bullishly, and follow-through bases form above the breakout pivot.
Topping / Distribution
Tighten stops — no new entries
Criteria
- • Still looks like Stage 2 but deteriorating
- • Price repeatedly violates SMA50, then recovers
- • Volume heavier on down days than up days
- • MAs starting to flatten or cross bearishly
Institutions quietly sell to retail who see the uptrend and buy late. Price stays elevated while distribution happens. Classic sign: stock makes new highs on low volume, then reverses hard. This is where most retail traders get trapped.
Example
Price near 52W high but RSI diverging, up-moves on light volume, down-moves on heavy volume.
Declining / Markdown
Avoid — no bottom fishing
Criteria
- • Price < SMA200 (below the line)
- • SMA200 slope falling > 1% over 20 days
- • All MAs stacked bearishly: SMA50 < SMA150 < SMA200
- • Lower highs and lower lows
Sellers are in control. Every rally is sold into. Bottoms are impossible to predict reliably — stocks can stay in Stage 4 for years. The only correct action is to wait for Stage 1 base formation before re-evaluating.
Example
Typical example: price stays below SMA200, rallies fail near resistance, and the long-term average keeps trending lower.
Stage Transition Signals
S4 → S1 (Watch for)
- • SMA200 stops declining, flattens
- • Price stops making lower lows
- • Volume dries up (sellers exhausted)
- • Takes weeks to months to confirm
S1 → S2 (Entry trigger)
- • Price breaks above SMA200 on volume
- • SMA200 slope turns positive (>0.5%)
- • SMA50 crosses above SMA150
- • VCP breakout above pivot = entry
S2 → S3 (Warning signs)
- • Price closes below SMA50 multiple times
- • RS Rating drops below 70
- • Volume pattern inverts (heavy down days)
- • Tighten stops to breakeven or trail
SEPA 8 Criteria (Stage 2 Confirmation)
Once in Stage 2, all 8 SEPA criteria must be met for a valid setup. Missing even one criterion lowers the probability of success significantly.
# Risk Management Framework
The 10 Layers of Protection (L1-L10)
Every signal passes through 10 independent risk checks. A single hard rejection stops the trade. This defense-in-depth approach ensures no single point of failure can cause catastrophic losses.
Portfolio should never be fully directional. Even in strong trends, keeping 40% cash or opposite exposure protects against sudden reversals. March 2020 crash happened in days — fully long portfolios were decimated.
Action: Reduces position size or blocks new trades in dominant direction
Herfindahl-Hirschman Index measures concentration. HHI = Σ(weight²) × 10000. Score >2500 means too concentrated. Diversification is the only free lunch in finance.
Action: Blocks new positions in overweight symbols
Gift Nifty (SGX Nifty) trades before Indian markets open. Large gaps between Gift Nifty and previous close indicate overnight sentiment shift. Trading against this gap has poor odds.
Action: Adjusts position size based on gap direction alignment
India VIX > 25 indicates fear/uncertainty. Options become expensive, whipsaws increase. Capital preservation is priority in high-VIX regimes. We reduce position sizes by 30-50%.
Action: Scales down position sizes, tightens stops
Sector correlation can wipe out diversification benefits. Banking stocks move together, IT stocks move together. Even with 10 stocks, if all are banking, it's effectively one bet.
Action: Blocks new positions in overweight sectors
Gamma risk explodes near expiry. Options can swing 50% in minutes. Weekend theta decay is also priced in on Fridays. We avoid positions expiring within 2 days.
Action: Blocks positions in near-expiry contracts
Kelly Criterion optimizes long-term growth but is too aggressive. We use 10% of Kelly as base, then adjust for volatility using ATR. High ATR = smaller position.
Action: Calculates optimal position size
Earnings are binary events with unpredictable outcomes. Even good results can cause selloffs (sell the news). IV crush post-earnings destroys option buyers. We avoid this lottery.
Action: Blocks positions in stocks with upcoming earnings
If daily theta > 2% of position value, time decay is eating profits too fast. Position needs management — roll to further expiry or close.
Action: Warns user, suggests rolling or closing
Crude +5%, Gold +3%, or Natural Gas +8% moves affect Indian markets significantly. OMCs suffer from crude spikes, inflation expectations shift. We reduce exposure during commodity volatility.
Action: Reduces exposure 20-50% based on spike severity
Position Sizing: The Kelly Criterion
The Kelly Criterion determines optimal bet size to maximize long-term growth:
Kelly % = (Win Rate × Avg Win - Loss Rate × Avg Loss) / Avg Win
Example: 60% win rate, 1.5:1 reward-risk
Kelly = (0.60 × 1.5 - 0.40 × 1) / 1.5 = 33%
We use 10% of Kelly (fractional Kelly)
Position Size = 33% × 0.10 = 3.3% of capital
Full Kelly is mathematically optimal but psychologically brutal — 30%+ drawdowns are common. Fractional Kelly (10-25%) sacrifices some returns for much smoother equity curve.
Stop Loss Philosophy
We use ATR-based stops rather than fixed percentages. A volatile stock needs wider stops; a stable stock needs tighter stops. The formula:
Stop Distance = 2 × ATR(14)
Example: Stock at ₹1000, ATR = ₹25
Stop Loss = ₹1000 - (2 × ₹25) = ₹950
The 2× ATR stop gives enough room for normal volatility while protecting against adverse moves. Stops are placed with the broker immediately (bracket orders) — not just monitored in code.
# Multi-Agent Analysis System
Why Multiple Agents?
Single-model AI systems suffer from confirmation bias — they find evidence supporting their initial hypothesis. Our adversarial multi-agent system forces rigorous debate:
- Bull Agent — Incentivized to find bullish evidence
- Bear Agent — Incentivized to find bearish evidence
- Skeptic Agent — Neutral judge who stress-tests both sides
This mirrors how institutional investment committees work — analysts present opposing views, and a committee decides. The debate process surfaces risks that single analysis might miss.
Bull Thesis Agent
Build the bullish caseInputs
• Price data
• Fundamentals
• News sentiment
• Options flow
Outputs
• Thesis statement
• Supporting evidence
• Catalysts
• Price targets
• Confidence score
Searches for positive signals: improving margins, sector tailwinds, institutional accumulation, positive news sentiment. Builds narrative explaining why stock should rise.
Bear Thesis Agent
Build the bearish caseInputs
• Price data
• Fundamentals
• News sentiment
• Risk factors
Outputs
• Thesis statement
• Risk factors
• Red flags
• Downside targets
• Confidence score
Searches for negative signals: deteriorating fundamentals, sector headwinds, insider selling, negative news. Identifies what could go wrong and why current price may be unjustified.
Skeptic Agent
Cross-examine and judgeInputs
• Bull thesis
• Bear thesis
• Questions to challenge each
Outputs
• Verdict (proceed/no_trade/lower_confidence)
• Score (0-1)
• Concerns
• Required changes
Asks probing questions to both sides. Evaluates quality of evidence and reasoning. Identifies gaps in analysis. Issues final verdict based on which side has stronger, more defensible position.
Technical Options Agent
Design option strategiesInputs
• Verdict
• Conviction level
• IV rank
• VIX level
• Available strikes
Outputs
• Candidate strategies
• Greeks analysis
• POP calculations
• Risk/reward profiles
Based on conviction and IV regime, selects appropriate strategy (spreads, condors, naked). Calculates Greeks, POP, max profit/loss. Considers liquidity and bid-ask spreads.
Risk Engine
Validate and size positionsInputs
• Selected strategy
• Portfolio state
• L1-L10 controls
Outputs
• Approved/Rejected
• Position size
• Exit rules
• Reason codes
Runs strategy through all 10 risk controls. Calculates position size using fractional Kelly. Sets stop loss and take profit levels. Generates trade ticket if approved.
Debate Depth Options
quick
Single round, minimal cross-examination. ~30 seconds. Use for screening many stocks.
normal
Full debate with cross-examination and rebuttals. ~2 minutes. Standard for trade decisions.
deep
Extended debate with multiple critique rounds. ~5 minutes. For large positions or uncertain situations.
# API Reference
Key Endpoints
# Glossary
AI Hedge Fund v1.0.0 | Built for Indian F&O Markets (NSE/BSE)
This documentation is for educational purposes. Trading involves risk of loss.