AI HEDGE

Documentation

Complete guide to the AI Hedge Fund trading platform — theory, strategies, and implementation

# Quick Start

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.

1

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.

Bullish:Current period historically shows >60% win rate with positive expectancy
Bearish:Current period historically shows <40% win rate with negative expectancy
2

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.

Bullish:Price > 20 EMA > 50 EMA > 200 EMA, all EMAs sloping up
Bearish:Price < 20 EMA < 50 EMA < 200 EMA, all EMAs sloping down
3

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.

Bullish:RSI > 50 with no bearish divergence, or bullish divergence forming at lows
Bearish:RSI < 50 with no bullish divergence, or bearish divergence forming at highs
4

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.

Bullish:Breaking above resistance with volume, or bouncing off support
Bearish:Breaking below support with volume, or rejecting at resistance
5

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.

Bullish:Volume expanding on up days, contracting on down days (accumulation)
Bearish:Volume expanding on down days, contracting on up days (distribution)
6

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.

Bullish:MACD above signal line, ADX > 25 and rising, positive ROC
Bearish:MACD below signal line, ADX > 25 and rising, negative ROC
7

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.

Bullish:Volatility contracting after expansion, price near lower band in uptrend
Bearish:Volatility contracting after expansion, price near upper band in downtrend
8

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.

Bullish:Stock outperforming Nifty 50 over 20 days
Bearish:Stock underperforming Nifty 50 over 20 days
9

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.

Bullish:Bullish reversal patterns at support (hammer, morning star, bullish engulfing)
Bearish:Bearish reversal patterns at resistance (shooting star, evening star, bearish engulfing)
10

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.

Bullish:Net FII buying, especially when DIIs are neutral or selling
Bearish:Net FII selling, especially when DIIs are buying (smart money exiting)
11

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.

Bullish:PCR > 1.2 (excessive puts = contrarian bullish), call OI building above price
Bearish:PCR < 0.7 (excessive calls = contrarian bearish), put OI building below price

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.

S1 (base) → S2 (uptrend) → S3 (top) → S4 (downtrend) → S1 again
S1

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.

S2

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.

S3

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.

S4

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.

1.Price > 150D SMA and 200D SMA
2.150D SMA > 200D SMA (medium-term above long-term)
3.200D SMA trending up for at least 30 days
4.50D SMA > 150D SMA and 200D SMA (full bullish stack)
5.Price > 50D SMA (above near-term average)
6.Price within 25% of 52-week high (near the top)
7.Price at least 30% above 52-week low (momentum confirmed)
8.RS Rating ≥ 70 (outperforming at least 70% of Nifty stocks)

# 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.

L1Direction LimitMax 60% one direction

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

L2Concentration (HHI)HHI < 2500

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

L3Pre-Market SentimentGift Nifty alignment

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

L4VIX RegimeReduce at VIX > 25

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

L5Sector LimitMax 40% per sector

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

L6Expiry BufferMin 2 days to expiry

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

L7Position SizingFractional Kelly + ATR

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

L8Earnings BlockNo trades 2 days pre-earnings

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

L9Theta Decay WarningAlert at >2% daily decay

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

L10Commodity RegimeReduce on commodity spikes

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 case

Inputs

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 case

Inputs

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 judge

Inputs

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 strategies

Inputs

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 positions

Inputs

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

POST/api/run-analysis-streamSSE stream for real-time analysis progress
GET/api/runs/{id}/full-stateComplete analysis state including all agent outputs
GET/api/signals/generateGenerate 11-Factor signals for F&O stocks
GET/api/newsMarket news with sentiment (5 min cache)
POST/api/reports/generateGenerate PDF analysis report

# Glossary

ATMAt-The-Money — option strike closest to current stock price
ITMIn-The-Money — option with intrinsic value (call: strike < price)
OTMOut-of-The-Money — option with no intrinsic value
IVImplied Volatility — market's expectation of future volatility
IV RankCurrent IV percentile over past year (0-100)
PCRPut-Call Ratio — total put OI / total call OI
OIOpen Interest — total outstanding option contracts
Max PainStrike where option writers profit most at expiry
ATRAverage True Range — volatility measure
EMAExponential Moving Average — weighted price average
RSIRelative Strength Index — momentum oscillator (0-100)
MACDMoving Average Convergence Divergence — trend indicator
FIIForeign Institutional Investors
DIIDomestic Institutional Investors
HHIHerfindahl-Hirschman Index — concentration measure
KellyKelly Criterion — optimal position sizing formula

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.