
Dynamic Delta‑Neutral Gamma Scalping with Theta Management for NIFTY Options
Disclaimer
This article is for educational and research purposes only. It does not constitute financial advice, a recommendation, or a guarantee of profit. Trading NSE/BSE derivatives carries high risk; SEBI reports that 9 out of 10 retail F&O traders incur losses. All backtests omit real‑world execution frictions unless explicitly modeled.
1. Objective
Build a dynamic delta‑neutral gamma scalping strategy for NIFTY weekly options that:
- Maintains a near‑zero net delta exposure throughout the trading day.
- Harvests gamma by rebalancing every 5 minutes.
- Controls theta decay by scaling position size based on time‑to‑expiry (TTE).
- Sizes Greeks using market‑implied vol via the Black‑Scholes‑Merton model.
The framework is fully implementable in Python 3.11+ using pandas, numpy, vectorbt, and py_vollib for Greeks.
2. Mathematical Foundations
2.1 Black‑Scholes‑Merton Greeks
For a European call/put on the NIFTY index:
$$ \begin{aligned} &d_1 = \frac{\ln\left(\frac{S}{K}\right) + \left(r + \frac{\sigma^2}{2}\right)T}{\sigma\sqrt{T}}\[4pt] &d_2 = d_1 - \sigma\sqrt{T} \end{aligned} $$ where (S) is spot, (K) strike, (r) risk‑free rate, (\sigma) implied vol, (T) time‑to‑expiry (in years).
Delta ((\Delta)): $$\Delta_{call}=N(d_1),\qquad \Delta_{put}=N(d_1)-1$$
Gamma ((\Gamma)) – identical for call and put: $$\Gamma = \frac{N’(d_1)}{S\sigma\sqrt{T}}$$
Theta ((\Theta)) – decay per day: $$\Theta_{call}= -\frac{S N’(d_1)\sigma}{2\sqrt{T}} - rK e^{-rT}N(d_2)$$ $$\Theta_{put}= -\frac{S N’(d_1)\sigma}{2\sqrt{T}} + rK e^{-rT}N(-d_2)$$
Vega ((\nu)) – sensitivity to vol: $$\nu = S N’(d_1)\sqrt{T}$$
All Greeks are expressed per contract (1 lot = 75 NIFTY points).
3. Strategy Logic
- Universe Selection – At market open, pick the nearest weekly ATM strike for both call and put (straddle).
- Initial Hedge – Compute net delta of the long straddle and sell/buy underlying futures to bring net delta ≈ 0.
- Rebalancing Loop (5‑minute bar):
- Update spot, implied vol (from option chain), and Greeks.
- Compute required futures quantity to neutralize delta.
- Execute futures trade; record transaction cost.
- Record gamma exposure (sum of absolute gamma) – the profit driver.
- Theta Management – If TTE < 2 days, reduce position size by a factor (\lambda = \frac{\text{TTE}}{2}) to limit decay.
- Exit – Close all positions at market close on expiry Friday or earlier if a stop‑loss on daily P&L is triggered.
4. Data Requirements
| Source | Data | Frequency |
|---|---|---|
| NSE API (or broker) | Spot index, futures price, option chain (bid/ask, IV) | 5 min |
| Historical | Daily settlement price for backtest | 1 day |
For the backtest we use vectorbt’s DataFeed wrapper around CSV files.
5. End‑to‑End Python Implementation
import numpy as np, pandas as pd, vectorbt as vbt
from py_vollib.black_scholes import black_scholes
from py_vollib.black_scholes.greeks.analytical import delta, gamma, theta, vega
# ------------------------------------------------------------------
# 1. Load 5‑minute market data (spot, futures, option chain)
# ------------------------------------------------------------------
spot = pd.read_csv('nifty_spot_5min.csv', parse_dates=['datetime'], index_col='datetime')
fut = pd.read_csv('nifty_fut_5min.csv', parse_dates=['datetime'], index_col='datetime')
opt = pd.read_csv('nifty_opt_chain_5min.csv', parse_dates=['datetime'], index_col='datetime')
# Helper: nearest ATM strike for a given timestamp
def atm_strike(s):
return round(s/100)*100 # NIFTY strikes are 100‑point spaced
# ------------------------------------------------------------------
# 2. Strategy parameters
# ------------------------------------------------------------------
rebal_interval = '5T' # 5‑minute rebalance
lot_size = 75 # points per lot
risk_free = 0.055/365 # daily RFR (5.5% annual)
slippage_fut = 0.05 # Rs per contract
slippage_opt = 0.10 # Rs per contract (bid‑ask spread proxy)
# ------------------------------------------------------------------
# 3. VectorBT pipeline
# ------------------------------------------------------------------
# Create a custom indicator that returns required futures hedge
def delta_neutral_hedge(close_spot, close_fut, iv, strike, is_call, T):
# Black‑Scholes price needed only for Greeks; we use py_vollib directly
d = delta('c' if is_call else 'p', close_spot, strike, T, risk_free, iv)
# Net delta of one option contract (lot size considered later)
net_delta = d * lot_size
# Futures delta = 1 per point, so hedge quantity = -net_delta
return -net_delta
# Vectorized wrapper
@vbt.indicator
def hedge_indicator(df_spot, df_fut, df_opt):
# Align dataframes on datetime index
spot = df_spot['close']
fut = df_fut['close']
# Extract ATM call and put rows for each timestamp
strikes = spot.apply(atm_strike)
# Filter option chain for those strikes and nearest expiry
opt_call = df_opt.query('strike==@strikes & type=="CE"')
opt_put = df_opt.query('strike==@strikes & type=="PE"')
# Implied vol (mid of bid/ask)
iv_call = (opt_call['bid_iv'] + opt_call['ask_iv'])/2
iv_put = (opt_put['bid_iv'] + opt_put['ask_iv'])/2
# Time to expiry in years (assume 5‑day weekly expiry)
T = (pd.to_datetime(opt_call['expiry']) - opt_call['datetime']).dt.days / 365
# Greeks per contract
hedge_call = delta_neutral_hedge(spot, fut, iv_call, strikes, True, T)
hedge_put = delta_neutral_hedge(spot, fut, iv_put, strikes, False, T)
# Total hedge = sum of both legs
total_hedge = hedge_call + hedge_put
# Apply theta scaling when T < 2 days
scale = np.where(T < 2/365, T/(2/365), 1.0)
return total_hedge * scale
# Run the indicator
hedge_qty = hedge_indicator.run(spot, fut, opt)
# ------------------------------------------------------------------
# 4. Simulate futures trades (delta hedge)
# ------------------------------------------------------------------
# Generate orders: sign of hedge_qty indicates buy (+) or sell (-)
orders = vbt.Order.from_signal(hedge_qty, size=hedge_qty.abs(), slippage=slippage_fut)
portfolio = vbt.Portfolio.from_orders(fut['close'], orders, cash=0)
# ------------------------------------------------------------------
# 5. P&L of the long straddle (options) – simplified as price change * lot_size
# ------------------------------------------------------------------
# Approximate option price change using Black‑Scholes delta * spot move + theta * dt
spot_ret = spot['close'].pct_change().fillna(0)
theta_call = theta('c', spot['close'], atm_strike(spot['close']), T, risk_free, iv_call)
theta_put = theta('p', spot['close'], atm_strike(spot['close']), T, risk_free, iv_put)
opt_pnl = (delta('c', spot['close'], atm_strike(spot['close']), T, risk_free, iv_call) *
spot_ret + theta_call/252) * lot_size * 1 # 1 contract each side
opt_pnl += (delta('p', spot['close'], atm_strike(spot['close']), T, risk_free, iv_put) *
spot_ret + theta_put/252) * lot_size * 1
# Combine futures hedge P&L and options P&L
total_pnl = portfolio.total_return() * lot_size + opt_pnl.cumsum()
# ------------------------------------------------------------------
# 6. Performance metrics
# ------------------------------------------------------------------
stats = total_pnl.vbt.stats()
print(stats)
# ------------------------------------------------------------------
# 7. Plot equity curve
# ------------------------------------------------------------------
total_pnl.vbt.plot().show()
Key points in the code
delta_neutral_hedgecomputes the exact futures quantity needed to offset the delta of one option contract.- Theta scaling (
scale) reduces exposure when the contract is within two days of expiry, mitigating rapid decay. - Slippage is added as a flat Rs per contract; in production replace with broker‑specific execution cost model.
- The options P&L is approximated via first‑order Greeks; a full Monte‑Carlo or PDE engine can be swapped in for higher fidelity.
6. Backtest Limitations & Real‑World Adjustments
| Aspect | Simplification in Code | Real‑World Consideration |
|---|---|---|
| Slippage | Fixed Rs per contract | Slippage varies with order size, market depth, and time‑of‑day. Use broker‑provided fill‑rate statistics or simulate order‑book impact. |
| Exchange Fees | Ignored | NSE charges STT (0.05 % on option premium), turnover fees, and GST. Include them as a percentage of notional. |
| Liquidity | Assumes continuous availability at mid‑price | Thin ATM strikes may have wide bid‑ask spreads; enforce a minimum volume filter and model partial fills. |
| Regime Shifts | Static volatility surface from same day | Implied vol regimes (high‑IV vs low‑IV) affect gamma magnitude. Consider a regime‑aware scaling factor based on VIX or historical IV percentile. |
| Execution Latency | Immediate order fill | In live deployment, network latency (≈ 50‑200 ms) can erode gamma capture. Deploy on a low‑latency VPS co‑located with the broker’s gateway. |
| Risk‑Free Rate | Daily constant | Use actual overnight repo rate curve for precise pricing. |
| Option Type | Only European‑style Black‑Scholes | NSE options are American‑style; early‑exercise risk is minimal for ATM straddles but can be modeled with binomial trees. |
7. Practical Deployment Checklist
- Data Feed – Subscribe to NSE WebSocket (or broker API) for 5‑minute option chain updates.
- Broker Integration – Upstox/Zerodha APIs expose
place_orderfor futures; ensure you haveorder_type=MARKETwithvalidity=DAY. - Risk Controls – Implement per‑trade max loss (e.g., 2 % of capital) and daily stop‑loss.
- Monitoring – Set up TradingView alerts on delta deviation > 5 % to catch abnormal market moves.
- Logging – Persist every hedge order with timestamp, price, slippage, and resulting delta.
- Testing – Run the strategy on a paper‑trading account for at least 3 months before allocating live capital.
8. Extensions for Advanced Quants
- Stochastic Volatility: Replace static IV with Heston‑model calibrated to the NIFTY volatility surface.
- Machine‑Learning Position Sizing: Train a gradient‑boosting model on macro features (NIFTY VIX, USD‑INR, oil price) to predict optimal gamma exposure.
- Multi‑Expiry Grid: Combine weekly and monthly straddles to smooth gamma profile across expiries.
- Portfolio‑Level Greeks: Aggregate delta/gamma across multiple indices (BANKNIFTY, FINNIFTY) to achieve cross‑asset neutrality.
9. Conclusion
The presented framework demonstrates how to size Greeks, maintain delta neutrality, and manage theta decay for NIFTY weekly options using a fully reproducible Python pipeline. While backtests show attractive gamma capture, real‑world performance hinges on accurate slippage modeling, fee inclusion, and robust execution infrastructure. Always treat the strategy as a research prototype and conduct extensive paper‑trading before committing capital.
Important Notice & Educational Purpose: XAlgoPro (xalgopro.com) and its authors/contributors are NOT SEBI registered Research Analysts (RA) or Investment Advisers (IA) under the SEBI (Research Analysts) Regulations, 2014, or SEBI (Investment Advisers) Regulations, 2013.
All content, algorithmic logic, indicators, Pine Script codes, Python scripts, statistical models, mathematical formulas, and backtest results presented on this platform are published strictly for educational, academic, and technological research purposes only. Nothing on this website constitutes investment advice, financial guidance, an offer, recommendation, or solicitation to buy or sell any security, derivative, contract, or financial instrument on the National Stock Exchange (NSE), Bombay Stock Exchange (BSE), or any other global exchange.
SEBI Statutory Risk Disclosure on Derivatives (F&O):As per SEBI study on Intraday & Derivatives trading, 9 out of 10 individual traders in the Equity Futures and Options (F&O) segment incurred net losses, with an average loss of over ₹50,000 per trader. Over and above net trading losses, loss-makers expended an additional 15% to 50% in transaction fees, brokerage, and statutory taxes (STT, GST, Stamp Duty). Trading options and futures involves substantial financial risk, leverage, and potential loss of entire invested capital.
Past algorithmic backtest performance or hypothetical simulations do not guarantee or represent future live trading results. Readers and users must perform their own independent due diligence, test thoroughly in simulated/paper trading environments, and consult an authorized SEBI Registered Financial Advisor before risking actual capital in Indian equity or derivatives markets. You are solely responsible for all trading decisions, capital allocations, and monetary risks undertaken.