델타 헤지 자동매매 전략

델타 헤지란?

델타 헤지(Delta Hedging)는 옵션 포지션의 방향성 리스크를 제거하기 위해 기초자산을 반대 방향으로 매매하는 리스크 관리 전략입니다. 옵션 그릭스(Greeks) 중 델타(Δ)를 0에 가깝게 유지함으로써, 기초자산 가격 변동에 관계없이 변동성(Volatility)시간가치(Theta)에서 수익을 추구합니다.

퀀트 헤지펀드와 마켓 메이커가 핵심적으로 사용하는 전략이며, 파이썬으로 자동화하면 리밸런싱 타이밍을 놓치지 않고 정밀하게 운영할 수 있습니다.

옵션 그릭스 핵심 정리

델타 헤지를 이해하려면 먼저 옵션 그릭스를 알아야 합니다. 각 지표가 옵션 가격에 미치는 영향을 정리합니다.

그릭 의미 헤지 활용
델타(Δ) 기초자산 $1 변동 시 옵션가 변화량 기초자산 매매로 중립화
감마(Γ) 델타의 변화 속도 리밸런싱 빈도 결정
쎄타(Θ) 시간 경과에 따른 옵션가 감소 옵션 매도 시 수익원
베가(ν) 내재변동성 1% 변동 시 옵션가 변화 변동성 매매 핵심 지표

블랙-숄즈 모델로 그릭스 계산

파이썬에서 블랙-숄즈 모형을 활용해 옵션 가격과 그릭스를 직접 계산하는 코드입니다.

import numpy as np
from scipy.stats import norm

class BlackScholes:
    @staticmethod
    def d1(S, K, T, r, sigma):
        return (np.log(S / K) + (r + sigma**2 / 2) * T) 
               / (sigma * np.sqrt(T))

    @staticmethod
    def d2(S, K, T, r, sigma):
        return BlackScholes.d1(S, K, T, r, sigma) 
               - sigma * np.sqrt(T)

    @staticmethod
    def call_price(S, K, T, r, sigma):
        d1 = BlackScholes.d1(S, K, T, r, sigma)
        d2 = BlackScholes.d2(S, K, T, r, sigma)
        return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)

    @staticmethod
    def delta(S, K, T, r, sigma, option_type='call'):
        d1 = BlackScholes.d1(S, K, T, r, sigma)
        if option_type == 'call':
            return norm.cdf(d1)
        return norm.cdf(d1) - 1

    @staticmethod
    def gamma(S, K, T, r, sigma):
        d1 = BlackScholes.d1(S, K, T, r, sigma)
        return norm.pdf(d1) / (S * sigma * np.sqrt(T))

    @staticmethod
    def theta(S, K, T, r, sigma, option_type='call'):
        d1 = BlackScholes.d1(S, K, T, r, sigma)
        d2 = BlackScholes.d2(S, K, T, r, sigma)
        term1 = -S * norm.pdf(d1) * sigma / (2 * np.sqrt(T))
        if option_type == 'call':
            return (term1 - r * K * np.exp(-r*T) * norm.cdf(d2)) / 365
        return (term1 + r * K * np.exp(-r*T) * norm.cdf(-d2)) / 365

    @staticmethod
    def vega(S, K, T, r, sigma):
        d1 = BlackScholes.d1(S, K, T, r, sigma)
        return S * norm.pdf(d1) * np.sqrt(T) / 100

델타 헤지 자동매매 봇 구현

아래는 옵션 포지션의 델타를 실시간 모니터링하고, 임계값을 초과하면 자동으로 기초자산을 매매하여 델타 중립(Delta Neutral)을 유지하는 봇입니다.

import time
from datetime import datetime

class DeltaHedgeBot:
    def __init__(self, exchange, symbol, option_positions):
        """
        :param exchange: ccxt 거래소 인스턴스
        :param symbol: 기초자산 심볼 (예: 'BTC/USDT')
        :param option_positions: 옵션 포지션 리스트
          [{'strike': K, 'expiry_days': T,
            'type': 'call'|'put', 'qty': n}, ...]
        """
        self.exchange = exchange
        self.symbol = symbol
        self.positions = option_positions
        self.hedge_qty = 0  # 현재 헤지용 기초자산 보유량
        self.r = 0.05       # 무위험 이자율
        self.logs = []

    def calculate_portfolio_delta(self, spot, sigma):
        """포트폴리오 전체 델타 계산"""
        total_delta = 0
        for pos in self.positions:
            T = pos['expiry_days'] / 365
            if T <= 0:
                continue
            d = BlackScholes.delta(
                spot, pos['strike'], T,
                self.r, sigma, pos['type']
            )
            total_delta += d * pos['qty']
        # 헤지 포지션의 델타 (기초자산 1단위 = 델타 1)
        total_delta += self.hedge_qty
        return total_delta

    def rebalance(self, spot, sigma, threshold=0.1):
        """
        포트폴리오 델타가 임계값 초과 시 리밸런싱
        :param threshold: 리밸런싱 트리거 (기본 0.1)
        """
        portfolio_delta = self.calculate_portfolio_delta(
            spot, sigma
        )

        if abs(portfolio_delta) < threshold:
            return None  # 리밸런싱 불필요

        # 델타 중립을 위해 필요한 기초자산 수량
        hedge_needed = -portfolio_delta

        side = 'buy' if hedge_needed > 0 else 'sell'
        qty = abs(hedge_needed)

        try:
            order = self.exchange.create_market_order(
                self.symbol, side, qty
            )
            self.hedge_qty += hedge_needed

            log_entry = {
                'time': datetime.now().isoformat(),
                'spot': spot,
                'delta_before': portfolio_delta,
                'action': f'{side} {qty:.4f}',
                'hedge_total': self.hedge_qty
            }
            self.logs.append(log_entry)
            return log_entry
        except Exception as e:
            print(f"[헤지 오류] {e}")
            return None

    def run(self, sigma=0.6, interval=60,
            threshold=0.1, max_hours=24):
        """
        델타 헤지 루프 실행
        :param sigma: 내재변동성
        :param interval: 체크 간격(초)
        :param max_hours: 최대 실행 시간
        """
        end_time = time.time() + max_hours * 3600
        print(f"[시작] 델타 헤지 봇 | σ={sigma} | "
              f"임계값={threshold}")

        while time.time() < end_time:
            ticker = self.exchange.fetch_ticker(self.symbol)
            spot = ticker['last']

            result = self.rebalance(spot, sigma, threshold)
            if result:
                print(f"[리밸런싱] {result['action']} "
                      f"@ {spot} | 델타: "
                      f"{result['delta_before']:.4f} → 0")

            # 만기일 업데이트
            for pos in self.positions:
                pos['expiry_days'] -= interval / 86400

            time.sleep(interval)

리밸런싱 빈도 최적화

델타 헤지에서 가장 중요한 결정은 얼마나 자주 리밸런싱할 것인가입니다. 너무 자주 하면 거래 비용이 수익을 잠식하고, 너무 드물면 리스크가 커집니다.

감마 기반 동적 임계값

포트폴리오 감마가 클수록 델타가 빠르게 변하므로, 리밸런싱 빈도를 높여야 합니다. 감마에 비례하여 임계값을 동적으로 조정하는 방식이 효과적입니다.

def dynamic_threshold(self, spot, sigma):
    """감마 기반 동적 리밸런싱 임계값"""
    total_gamma = 0
    for pos in self.positions:
        T = pos['expiry_days'] / 365
        if T <= 0:
            continue
        g = BlackScholes.gamma(
            spot, pos['strike'], T, self.r, sigma
        )
        total_gamma += abs(g * pos['qty'])

    # 감마가 높을수록 임계값 낮춤 (더 자주 리밸런싱)
    base_threshold = 0.15
    gamma_factor = max(0.3, 1 - total_gamma * spot)
    return base_threshold * gamma_factor

거래 비용 vs 헤지 오차 트레이드오프

리밸런싱 빈도 거래 비용 헤지 정확도 적합 상황
1분마다 매우 높음 최상 마켓 메이커
15분마다 중간 높음 적극적 헤지
1시간마다 낮음 중간 일반 투자자
델타 임계값 초과 시 최적 높음 권장 방식

실전 운영 주의사항

  • 내재변동성 업데이트 — 고정 σ가 아닌 실시간 IV를 반영해야 정확한 델타 계산 가능
  • 만기 근접 감마 리스크 — ATM 옵션의 만기가 가까워지면 감마가 급증하여 헤지 비용 폭증 (핀 리스크)
  • 점프 리스크 — 블랙-숄즈는 연속적 가격 변동을 가정하므로, 급등락 시 헤지 실패 가능
  • 배당·펀딩비 — 암호화폐 선물의 펀딩비나 주식 배당을 모델에 반영
  • 거래 비용 포함 — 수수료·슬리피지를 포함한 순 PnL로 성과 평가

델타 헤지 성과 측정

델타 헤지 전략의 성과는 헤지 PnL그릭스 노출로 평가합니다.

def calculate_pnl(self):
    """헤지 포트폴리오 총 손익 분석"""
    option_pnl = 0   # 옵션 포지션 시가평가 변동
    hedge_pnl = 0    # 기초자산 헤지 실현 손익
    trade_costs = 0  # 누적 거래 비용

    for log in self.logs:
        qty = float(log['action'].split()[1])
        trade_costs += qty * log['spot'] * 0.001  # 0.1% 수수료

    net_pnl = option_pnl + hedge_pnl - trade_costs
    return {
        'option_pnl': option_pnl,
        'hedge_pnl': hedge_pnl,
        'trade_costs': trade_costs,
        'net_pnl': net_pnl,
        'num_rebalances': len(self.logs)
    }

관련 글

위로 스크롤
WordPress Appliance - Powered by TurnKey Linux