Skip to content

aakash-code/GammaGEX

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GammaGEX 📊

Greek-Based Momentum Indicators for Options Trading

GammaGEX is a sophisticated Python application that analyzes option chain data to identify stock momentum using advanced Greek-based indicators. Built specifically for Indian markets, it integrates seamlessly with OpenAlgo and Upstox to provide real-time momentum analysis.


🎯 Features

Six Powerful Momentum Indicators

  1. Net Gamma Exposure (GEX) Analysis

    • Identifies market maker hedging behavior
    • Detects high/low momentum regimes
    • Finds critical "zero gamma" levels
  2. Delta-Weighted Volume Flow

    • Tracks institutional positioning
    • Identifies directional option flow
    • Confirms momentum trends
  3. Gamma Squeeze Detection

    • Identifies squeeze setups in real-time
    • Predicts explosive momentum moves
    • Monitors call walls and dealer positioning
  4. Vanna & Charm Analysis

    • Predicts momentum changes from volatility shifts
    • Analyzes delta decay patterns
    • Second-order Greek momentum prediction
  5. IV Skew Momentum

    • Tracks fear/complacency in options
    • Identifies skew-based reversals
    • Monitors put-call IV differentials
  6. Composite Momentum Score

    • Combines all indicators into single score (0-100)
    • Weighted scoring system
    • High-confidence signal generation

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • OpenAlgo instance running (http://127.0.0.1:5000)
  • Upstox broker account connected to OpenAlgo
  • OpenAlgo API key

Installation

# Clone the repository
git clone https://github.com/aakash-code/GammaGEX.git
cd GammaGEX

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Setup configuration
cp .env.example .env
# Edit .env and add your OpenAlgo API key

Configuration

Edit .env file:

# OpenAlgo Connection
OPENALGO_HOST=http://127.0.0.1:5000
OPENALGO_API_KEY=your_app_api_key_here

# Broker Configuration
BROKER=upstox

# Database
DATABASE_URL=sqlite:///data/gammagex.db

# Logging
LOG_LEVEL=INFO

Initialize Database

python scripts/setup_db.py

Run Momentum Monitor

# Monitor NIFTY
python scripts/monitor.py --symbol NIFTY --expiry current_week

# Monitor BANKNIFTY
python scripts/monitor.py --symbol BANKNIFTY --interval 30

# Monitor specific expiry
python scripts/monitor.py --symbol RELIANCE --expiry 17-JUL-25

📖 How It Works

The Momentum Scoring System

GammaGEX calculates a composite momentum score (0-100) using weighted contributions from multiple Greek-based indicators:

Momentum Score =
    (0.30 × GEX Signal) +
    (0.25 × Delta Flow Signal) +
    (0.20 × Gamma Squeeze Signal) +
    (0.15 × Vanna Signal) +
    (0.10 × IV Skew Signal)

Interpretation:

  • Score > 60: Bullish momentum
  • Score 40-60: Neutral/Range-bound
  • Score < 40: Bearish momentum

1. Net Gamma Exposure (GEX)

What it measures: Aggregate dealer gamma positions that dictate hedging behavior.

How it works:

For each strike:
    Call Gamma Exposure = Call OI × Call Gamma × 100 × Spot
    Put Gamma Exposure = Put OI × Put Gamma × 100 × Spot
    Net Gamma = Call GEX - Put GEX

Total GEX = Sum of all strikes

Signals:

  • Positive GEX: Dealers dampen moves → Low momentum, range-bound
  • Negative GEX: Dealers amplify moves → High momentum, breakout potential
  • Below Zero Gamma Level: Explosive momentum expected

2. Delta-Weighted Volume Flow

What it measures: Directional option positioning weighted by delta.

How it works:

Bullish Flow = (Call Buy Volume × Delta)
Bearish Flow = (Put Buy Volume × Delta)
Net Delta Flow = Bullish - Bearish

Signals:

  • Sustained positive flow → Institutional bullish positioning
  • Sustained negative flow → Institutional bearish positioning
  • Flow MA crossovers → Momentum shifts

3. Gamma Squeeze Detection

What it measures: Conditions that force dealers to buy/sell, creating self-reinforcing moves.

Conditions monitored:

  1. High call OI above current price
  2. Rising call gamma
  3. Low put/call ratio (delta-adjusted)
  4. Price approaching high-OI strikes

Squeeze Score Components:

  • Call OI concentration (30% weight)
  • Gamma trend (30% weight)
  • PCR delta-adjusted (20% weight)
  • Distance to max OI strike (20% weight)

4. Vanna & Charm

What they measure:

  • Vanna: How delta changes with volatility (∂Delta/∂IV)
  • Charm: How delta decays with time (∂Delta/∂Time)

Signals:

  • Rising IV + Positive Vanna → Delta increasing → Momentum building
  • High Charm → Delta decay → Momentum fading

5. IV Skew

What it measures: Put-Call implied volatility differential.

Formula:

IV Skew = (ATM Put IV - ATM Call IV) / Average IV

Signals:

  • Steepening skew → Fear building → Potential downward momentum
  • Flattening skew → Complacency → Potential upward momentum

🏗️ Architecture

GammaGEX/
├── src/
│   ├── connectors/          # OpenAlgo API & WebSocket clients
│   ├── models/              # Data models (Pydantic)
│   ├── calculators/         # Greek calculators & indicators
│   ├── storage/             # Database models & repositories
│   ├── services/            # Business logic orchestration
│   └── config.py            # Configuration management
├── scripts/
│   ├── setup_db.py          # Database initialization
│   └── monitor.py           # Real-time monitoring CLI
├── config/
│   ├── config.yaml          # Application config
│   └── symbols.yaml         # Symbols to track
├── data/                    # SQLite database
└── logs/                    # Application logs

📊 Data Flow

┌─────────────────┐
│  Upstox Broker  │
│   (Live Data)   │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  OpenAlgo API   │
│   (Middleware)  │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────────────┐
│           GammaGEX Engine           │
│                                     │
│  ┌──────────────────────────────┐  │
│  │    Option Chain Fetcher      │  │
│  └──────────────┬───────────────┘  │
│                 │                   │
│  ┌──────────────▼───────────────┐  │
│  │   Greek Calculators          │  │
│  │  • GEX                       │  │
│  │  • Delta Flow                │  │
│  │  • Gamma Squeeze             │  │
│  │  • Vanna/Charm               │  │
│  │  • IV Skew                   │  │
│  └──────────────┬───────────────┘  │
│                 │                   │
│  ┌──────────────▼───────────────┐  │
│  │  Momentum Scoring Engine     │  │
│  └──────────────┬───────────────┘  │
│                 │                   │
│  ┌──────────────▼───────────────┐  │
│  │   Signal Generator           │  │
│  └──────────────┬───────────────┘  │
│                 │                   │
│  ┌──────────────▼───────────────┐  │
│  │   Database Storage           │  │
│  └──────────────────────────────┘  │
└─────────────────────────────────────┘
         │
         ▼
┌─────────────────┐
│   CLI Monitor   │
│   Dashboard     │
└─────────────────┘

🔧 Configuration

Symbols Configuration (config/symbols.yaml)

symbols:
  - name: NIFTY
    exchange: NSE
    type: INDEX
    track_options: true
    lot_size: 75

  - name: BANKNIFTY
    exchange: NSE
    type: INDEX
    track_options: true
    lot_size: 30

# Default expiry to track
default_expiry: "current_week"

# Strike selection
strike_selection: "atm_range"

atm_range:
  above: 10  # Strikes above ATM
  below: 10  # Strikes below ATM

# Alert thresholds
alerts:
  momentum_score_high: 75
  momentum_score_low: 25
  gamma_squeeze_threshold: 70
  gex_regime_change: true

Momentum Weights

Customize indicator weights in code or config:

custom_weights = {
    'gex': 0.35,           # Increase GEX importance
    'delta_flow': 0.30,
    'gamma_squeeze': 0.20,
    'vanna_charm': 0.10,
    'iv_skew': 0.05,
}

calculator = MomentumScoreCalculator(custom_weights=custom_weights)

📈 Usage Examples

Command Line Interface

# Basic monitoring
python scripts/monitor.py --symbol NIFTY

# Custom update interval (30 seconds)
python scripts/monitor.py --symbol BANKNIFTY --interval 30

# Specific expiry
python scripts/monitor.py --symbol RELIANCE --expiry 17-JUL-25

# Different exchange
python scripts/monitor.py --symbol TCS --exchange NSE

Python API

from gammagex import GammaGEX
from connectors.openalgo_client import OpenAlgoClient
from calculators.momentum_score import MomentumScoreCalculator

# Initialize client
client = OpenAlgoClient(host="http://127.0.0.1:5000", api_key="your_key")

# Fetch option chain
chain = client.get_option_chain("NIFTY", "17-JUL-25")

# Calculate momentum
calculator = MomentumScoreCalculator()
momentum = calculator.calculate(chain)

print(f"Momentum Score: {momentum.score:.2f}")
print(f"Direction: {momentum.direction.value}")
print(f"Interpretation: {momentum.interpretation}")

# Get high-priority signals
signals = momentum.get_high_priority_signals(min_priority=7)
for signal in signals:
    print(f"{signal.signal_type.value}: {signal.description}")

🎨 Output Example

╭─────────────────────────────────────────────────────────────────╮
│  GammaGEX - Real-time Momentum Monitor                         │
│  Symbol: NIFTY | Expiry: 17-JUL-25 | Spot: ₹24,850 | 14:35:22 │
╰─────────────────────────────────────────────────────────────────╯

╭─── Momentum Score ─────────────────╮ ╭─── Component Scores ────────╮
│                                    │ │ Component       Score  Bar  │
│ 📈 BULLISH MOMENTUM                │ │ GEX             72.3   ████ │
│                                    │ │ Delta Flow      68.5   ███  │
│ Score: 71.5/100                    │ │ Gamma Squeeze   78.2   ████ │
│ ████████████████████████░░░░░      │ │ Vanna Charm     55.1   ███  │
│                                    │ │ IV Skew         48.3   ██   │
│ Strength: 0.43                     │ ╰─────────────────────────────╯
│ Confidence: 0.78                   │
│                                    │
│ Primary driver: gamma_squeeze      │
│ GEX Regime: Negative GEX -         │
│ market makers amplify moves        │
╰────────────────────────────────────╯

╭─── Active Signals ─────────────────────────────────────────────╮
│ 🟢 [gamma_squeeze] High squeeze risk at 25,000 strike         │
│ 🟢 [negative_gex] High momentum expected below zero gamma     │
│ 🟢 [delta_flow] Bullish institutional flow detected           │
╰────────────────────────────────────────────────────────────────╯

🗄️ Database Schema

GammaGEX stores all calculations for historical analysis:

  • option_chains: Option chain snapshots with Greeks
  • spot_prices: Underlying price history
  • momentum_indicators: Calculated momentum metrics
  • signals: Generated trading signals
  • alerts: System alerts
  • backtest_results: Backtesting performance

🔌 OpenAlgo Integration

GammaGEX requires a running OpenAlgo instance with Upstox connectivity.

OpenAlgo Setup

  1. Install OpenAlgo: https://docs.openalgo.in/
  2. Connect Upstox broker
  3. Generate API key
  4. Add API key to GammaGEX .env file

Available Endpoints Used

  • OptionSymbol API: Fetch option contracts
  • OptionGreeks API: Get Greeks (delta, gamma, vega, theta, rho, IV)
  • Quotes API: Real-time prices and OI
  • Expiry API: Available expiry dates
  • WebSocket: Real-time streaming (future feature)

🧪 Testing

# Run unit tests
pytest tests/

# Run with coverage
pytest --cov=src tests/

# Run specific test file
pytest tests/test_calculators/test_gex.py

🛣️ Roadmap

  • Core Greek calculators
  • Momentum scoring engine
  • Real-time CLI monitor
  • Database storage
  • WebSocket real-time streaming
  • Web dashboard (Streamlit/Dash)
  • Backtesting engine
  • REST API for external integration
  • Multi-symbol monitoring
  • Alert notifications (Telegram, Email)
  • Advanced charting
  • Machine learning momentum prediction

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


⚠️ Disclaimer

This software is for educational and research purposes only.

  • Not financial advice
  • Use at your own risk
  • Past performance does not guarantee future results
  • Always do your own research before trading
  • The authors assume no liability for any trading losses

📧 Contact

For questions, suggestions, or support:


🙏 Acknowledgments

  • OpenAlgo team for the excellent open-source trading platform
  • Upstox for broker API
  • Options trading community for inspiration

Built with ❤️ for the Indian options trading community

GammaGEX - Because Greeks Know Best!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages