top of page

Taking the Guesswork Out of Trading #13: Using QuantLib to Analyze GEX (Gamma Exposure)

  • Writer: Ognjen Vukovic
    Ognjen Vukovic
  • Aug 12, 2025
  • 3 min read
We are all Quants!
We are all Quants!

QuantLib, a C++ library with Python bindings, is widely used for pricing derivatives and calculating option Greeks, including gamma. It’s an ideal tool for traders looking to compute GEX programmatically. Here’s how you can use QuantLib to analyze GEX:



import QuantLib as ql

# Set up market data
spot_price = 100.0  # Current stock price
strike_price = 100.0  # ATM strike
volatility = 0.2  # 20% implied volatility
risk_free_rate = 0.05  # 5% interest rate
maturity = 0.25  # 3 months to expiration

# Define QuantLib objects
today = ql.Date(12, ql.August, 2025)
ql.Settings.instance().evaluationDate = today
maturity_date = today + int(maturity * 365)
spot = ql.QuoteHandle(ql.SimpleQuote(spot_price))
risk_free = ql.YieldTermStructureHandle(ql.FlatForward(today, risk_free_rate, ql.Actual365Fixed()))
vol = ql.BlackVolTermStructureHandle(ql.BlackConstantVol(today, ql.NullCalendar(), volatility, ql.Actual365Fixed()))
process = ql.BlackScholesProcess(spot, risk_free, vol)

# Define option
option_type = ql.Option.Call
payoff = ql.PlainVanillaPayoff(option_type, strike_price)
exercise = ql.EuropeanExercise(maturity_date)
option = ql.VanillaOption(payoff, exercise)

# Price and calculate Greeks
engine = ql.AnalyticEuropeanEngine(process)
option.setPricingEngine(engine)
gamma = option.gamma()

print(f"Gamma: {gamma}")

This code calculates the gamma for a single European call option. Repeat this for all options (calls and puts) across strikes and expirations for a given asset.


Step 2: Aggregate Gamma for GEX


To compute GEX, sum the gamma values across all options, weighted by open interest and contract size (typically 100 shares per contract). The formula for GEX is:


GEX = Σ (Gamma_i * OpenInterest_i * ContractSize * UnderlyingPrice * 0.01)

Where:


  • Gamma_i is the gamma of the i-th option.

  • OpenInterest_i is the open interest for that option.

  • ContractSize is typically 100 (shares per contract).

  • UnderlyingPrice is the current price of the stock.

  • The 0.01 factor accounts for a 1% price move.


Using QuantLib, you can loop through available options data (e.g., from a market data provider) to calculate gamma for each contract and aggregate them:


# Function to compute option gamma
def compute_option_gamma(option_data, current_spot_price):
    # Update spot price
    spot_quote = ql.QuoteHandle(ql.SimpleQuote(current_spot_price))

    # Create Black-Scholes process with updated spot
    process = ql.BlackScholesProcess(spot_quote, risk_free, vol)

    # Determine option type
    option_type = ql.Option.Call if option_data['type'] == 'call' else ql.Option.Put

    # Create option
    payoff = ql.PlainVanillaPayoff(option_type, option_data['strike'])
    exercise = ql.EuropeanExercise(maturity_date)
    option = ql.VanillaOption(payoff, exercise)

    # Set pricing engine and calculate gamma
    engine = ql.AnalyticEuropeanEngine(process)
    option.setPricingEngine(engine)

    return option.gamma()


# Example: Aggregate GEX (simplified)
def calculate_gex(options_data, spot_price):
    gex = 0.0
    contract_size = 100
    for option in options_data:
        gamma = compute_option_gamma(option, spot_price)
        open_interest = option['open_interest']
        gex += gamma * open_interest * contract_size * spot_price * 0.01
    return gex


# Hypothetical options data (strike, type, open_interest, etc.)
options_data = [
    {'strike': 100, 'type': 'call', 'open_interest': 500},
    {'strike': 100, 'type': 'put', 'open_interest': 300},
    # Add more options...
]

gex = calculate_gex(options_data, spot_price=100.0)
print(f"Total GEX: ${gex:,.2f}")

Step 3: Interpret GEX with QuantLib


  • Positive GEX: Indicates a long gamma environment, suggesting stability. Use QuantLib to identify strikes with high gamma to pinpoint support/resistance.

  • Negative GEX: Signals a short gamma environment, warning of potential volatility. QuantLib can help track real-time changes in gamma across strikes.

  • Key Levels: Use QuantLib to compute gamma for each strike and identify those with the highest gamma concentration, which act as price magnets.


Step 4: Integrate with Trading Strategies


QuantLib’s real-time capabilities (when paired with live market data) allow traders to:

  • Monitor GEX intraday to spot shifts in market maker positioning.

  • Combine GEX with other QuantLib outputs (e.g., delta, vega) for comprehensive analysis.

  • Automate trading signals based on GEX thresholds or gamma flip points (where GEX shifts from positive to negative).


For stock traders, use GEX-derived levels as support/resistance zones in conjunction with technical indicators like moving averages or RSI, calculated outside QuantLib.


Practical Considerations


GEX is dynamic, changing with price movements, open interest, and trading volume. Both options and stock traders should combine GEX with other tools, such as:


  • Options Traders: Use QuantLib to compute implied volatility and open interest alongside GEX for a holistic view.

  • Stock Traders: Pair GEX with volume profiles or order flow analysis to confirm key levels.


QuantLib requires access to reliable options data (e.g., via APIs like Bloomberg, CBOE, or Quandl) and familiarity with Python programming. Traders new to QuantLib can start with tutorials or resources like Luigi Ballabio’s Implementing QuantLib blog for practical guidance.


Conclusion


Gamma Exposure (GEX) bridges options and stock trading, revealing how market makers’ hedging drives price action and volatility. With QuantLib, traders can compute gamma and GEX with precision, identifying key levels and market conditions. For options traders, GEX informs strategies like range-bound or momentum trades. For stock traders, it highlights support, resistance, and potential volatility spikes. By integrating QuantLib’s computational power with GEX analysis, you can gain a competitive edge in navigating the dynamic interplay of options and stock markets. Dive into QuantLib, explore GEX, and elevate your trading strategy today!

Comments


bottom of page