암호화폐 거래에서 파생상품 데이터 분석은 시장 방향 예측과 리스크 관리에 핵심적인 역할을 합니다. 본 튜토리얼에서는 Tardis CSV 데이터셋을 활용하여 옵션 체인(Options Chain)과 자금费率(Funding Rate)를 분석하는 방법을 심층적으로 다룹니다. HolySheep AI를 활용한 실전 분석 워크플로우까지 포함되어 있습니다.
1. Tardis CSV 데이터셋 소개
Tardis Machine은 주요 암호화폐 거래소(Binance, Bybit, OKX 등)의 원시 시세 데이터를 CSV 형태로 제공하는 서비스입니다. 고빈도 거래 데이터,-funding rate 이력, 옵션 데이터 등을 포함하여 퀀트 트레이딩 및 시장 연구에 필수적인 리소스입니다.
2. 개발 환경 설정
# 필요한 패키지 설치
pip install pandas numpy matplotlib plotly requests
프로젝트 디렉토리 구조
project/
├── data/
│ ├── funding_rates/
│ └── options/
├── scripts/
│ ├── analyze_funding.py
│ └── analyze_options.py
└── outputs/
3. Tardis CSV 데이터 로드 및 전처리
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import os
class TardisDataLoader:
"""Tardis CSV 데이터 로더 클래스"""
def __init__(self, data_dir='./data'):
self.data_dir = data_dir
self.cache = {}
def load_funding_rate(self, exchange='binance', symbol='BTCUSDT',
start_date='2025-01-01', end_date='2025-12-31'):
"""바이낸스 BTC/USDT 펀딩费率 데이터 로드"""
file_path = f"{self.data_dir}/funding_rates/{exchange}_{symbol}_funding.csv"
# Tardis CSV 형식: timestamp, symbol, funding_rate, next_funding_time
df = pd.read_csv(file_path, parse_dates=['timestamp'])
# 날짜 범위 필터링
df = df[(df['timestamp'] >= start_date) & (df['timestamp'] <= end_date)]
# 펀딩费率 통계 계산
df['funding_pct_annual'] = df['funding_rate'] * 3 * 365 * 100
df['funding_direction'] = np.where(df['funding_rate'] > 0, '_LONG', '_SHORT')
return df
def load_options_chain(self, exchange='deribit', symbol='BTC',
expiry='2025-03-28'):
"""Deribit 옵션 체인 데이터 로드"""
file_path = f"{self.data_dir}/options/{exchange}_{symbol}_{expiry}.csv"
# 옵션 데이터: strike, option_type, bid, ask, iv, delta, gamma, vega
df = pd.read_csv(file_path)
# ATM(At-The-Money) 옵션 식별
spot_col = 'underlying_price' if 'underlying_price' in df.columns else 'spot'
df['moneyness'] = df['strike'] / df[spot_col]
df['option_category'] = pd.cut(df['moneyness'],
bins=[0, 0.95, 1.05, float('inf')],
labels=['ITM', 'ATM', 'OTM'])
return df
사용 예시
loader = TardisDataLoader()
btc_funding = loader.load_funding_rate(symbol='BTCUSDT')
btc_options = loader.load_options_chain(symbol='BTC', expiry='2025-03-28')
print(f"펀딩费率 데이터: {len(btc_funding)}건 로드됨")
print(f"평균 펀딩费率: {btc_funding['funding_rate'].mean():.6f}")
4. 펀딩费率 분석 및 시각화
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def analyze_funding_rate(funding_df, symbol='BTC'):
"""펀딩费率 상세 분석"""
# 1. 기본 통계
stats = {
'mean': funding_df['funding_rate'].mean(),
'std': funding_df['funding_rate'].std(),
'max': funding_df['funding_rate'].max(),
'min': funding_df['funding_rate'].min(),
'positive_rate': (funding_df['funding_rate'] > 0).mean() * 100
}
# 2. 일별/주별 집계
funding_df['date'] = funding_df['timestamp'].dt.date
daily_stats = funding_df.groupby('date').agg({
'funding_rate': ['mean', 'std', 'count'],
'funding_pct_annual': 'mean'
})
# 3. 극단값 감지 (이상치 탐지)
q1 = funding_df['funding_rate'].quantile(0.25)
q3 = funding_df['funding_rate'].quantile(0.75)
iqr = q3 - q1
outliers = funding_df[
(funding_df['funding_rate'] < q1 - 1.5*iqr) |
(funding_df['funding_rate'] > q3 + 1.5*iqr)
]
print(f"\n=== {symbol} 펀딩费率 분석 결과 ===")
print(f"평균: {stats['mean']:.6f} ({stats['mean']*100:.4f}%)")
print(f"연간 환산: {stats['mean']*3*365*100:.2f}%")
print(f"표준편차: {stats['std']:.6f}")
print(f"양수 비율: {stats['positive_rate']:.1f}%")
print(f"이상치 횟수: {len(outliers)}")
return stats, daily_stats, outliers
def plot_funding_analysis(funding_df, output_path='./outputs/funding_analysis.png'):
"""펀딩费率 시각화"""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. 시계열 플롯
ax1 = axes[0, 0]
funding_df.plot(x='timestamp', y='funding_rate', ax=ax1,
color='blue', alpha=0.7, linewidth=0.8)
ax1.axhline(y=0, color='red', linestyle='--', linewidth=1)
ax1.set_title('펀딩费率 시계열 (8시간 단위)')
ax1.set_ylabel('펀딩费率')
ax1.grid(True, alpha=0.3)
# 2. 연간 환산 펀딩费率 분포
ax2 = axes[0, 1]
funding_df['funding_pct_annual'].hist(bins=50, ax=ax2, color='green', alpha=0.7)
ax2.axvline(x=funding_df['funding_pct_annual'].mean(), color='red',
linestyle='--', label=f"평균: {funding_df['funding_pct_annual'].mean():.1f}%")
ax2.set_title('연간 환산 펀딩费率 분포')
ax2.set_xlabel('연간 펀딩费率 (%)')
ax2.legend()
# 3. 롱/숏 비율 (양수 비율)
ax3 = axes[1, 0]
funding_df['date'] = funding_df['timestamp'].dt.date
daily_positive = funding_df.groupby('date')['funding_rate'].apply(
lambda x: (x > 0).mean() * 100
)
daily_positive.plot(ax=ax3, color='purple', linewidth=0.8)
ax3.axhline(y=50, color='orange', linestyle='--', label='50% 기준선')
ax3.set_title('일별 양수(롱우세) 비율')
ax3.set_ylabel('비율 (%)')
ax3.set_ylim(0, 100)
ax3.legend()
# 4. 일별 평균 펀딩费率
ax4 = axes[1, 1]
daily_mean = funding_df.groupby('date')['funding_rate'].mean()
daily_mean.plot(ax=ax4, color='teal', linewidth=1.2)
ax4.fill_between(daily_mean.index, daily_mean.values, alpha=0.3, color='teal')
ax4.set_title('일별 평균 펀딩费率')
ax4.set_ylabel('평균 펀딩费率')
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.show()
return fig
분석 실행
stats, daily_stats, outliers = analyze_funding_rate(btc_funding)
plot_funding_analysis(btc_funding)
5. 옵션 체인 분석
import numpy as np
from scipy.stats import norm
class OptionsAnalyzer:
"""옵션 체인 분석기"""
def __init__(self, spot_price, risk_free_rate=0.05):
self.spot = spot_price
self.r = risk_free_rate
def calculate_greeks(self, strike, time_to_expiry, iv, option_type='call'):
"""그릭 계산 (BSM 모델)"""
T = time_to_expiry
K = strike
sigma = iv
d1 = (np.log(self.spot / K) + (self.r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
if option_type == 'call':
delta = norm.cdf(d1)
price = self.spot * norm.cdf(d1) - K * np.exp(-self.r * T) * norm.cdf(d2)
else:
delta = norm.cdf(d1) - 1
price = K * np.exp(-self.r * T) * norm.cdf(-d2) - self.spot * norm.cdf(-d1)
gamma = norm.pdf(d1) / (self.spot * sigma * np.sqrt(T))
vega = self.spot * norm.pdf(d1) * np.sqrt(T) / 100 # 1% IV 기준
theta = (-self.spot * norm.pdf(d1) * sigma / (2 * np.sqrt(T))
- self.r * K * np.exp(-self.r * T) * norm.cdf(d2 if option_type=='call' else -d2)) / 365
return {
'price': price,
'delta': delta,
'gamma': gamma,
'vega': vega,
'theta': theta
}
def build_options_chain(self, options_df):
"""옵션 체인 구축 및 정리"""
# ATM 근처 스트라이크 필터
atm_range = 0.1 # ±10%
mask = (options_df['moneyness'] >= 1 - atm_range) & \
(options_df['moneyness'] <= 1 + atm_range)
filtered = options_df[mask].copy()
# 콜/풋 분할
calls = filtered[filtered['option_type'] == 'call'].sort_values('strike')
puts = filtered[filtered['option_type'] == 'put'].sort_values('strike')
# 미결제약정(Open Interest) 기반 강도 계산
total_oi = options_df['open_interest'].sum()
calls['oi_weight'] = calls['open_interest'] / total_oi * 100
puts['oi_weight'] = puts['open_interest'] / total_oi * 100
# PCR (Put/Call Ratio)
put_oi = puts['open_interest'].sum()
call_oi = calls['open_interest'].sum()
pcr = put_oi / call_oi if call_oi > 0 else 0
print(f"\n=== 옵션 체인 분석 결과 ===")
print(f"ATM 스트라이크: {self.spot * filtered['moneyness'].median():.0f}")
print(f"콜 미결제약정: {call_oi:,.0f}")
print(f"풋 미결제약정: {put_oi:,.0f}")
print(f"PCR (Put/Call Ratio): {pcr:.3f}")
# 강도 분석
if pcr > 1.2:
print("解读: 약세 시장 인식 강함 (풋 우세)")
elif pcr < 0.7:
print("解读: 강세 시장 인식 강함 (콜 우세)")
else:
print("解读: 중립적 시장 인식")
return calls, puts, pcr
def calculate_max_pain(self, options_df):
"""맥스페인 스트라이크 계산"""
strikes = options_df['strike'].unique()
pains = []
for strike in strikes:
call_value = options_df[
(options_df['option_type'] == 'call') &
(options_df['strike'] >= strike)
].eval('(strike - @strike) * open_interest').sum()
put_value = options_df[
(options_df['option_type'] == 'put') &
(options_df['strike'] <= strike)
].eval('(@strike - strike) * open_interest').sum()
total_pain = call_value + put_value
pains.append({'strike': strike, 'pain': total_pain})
pain_df = pd.DataFrame(pains)
max_pain = pain_df.loc[pain_df['pain'].idxmin(), 'strike']
print(f"맥스페인 스트라이크: {max_pain}")
return max_pain
사용 예시
spot_btc = 65000 # BTC 현물 가격 예시
analyzer = OptionsAnalyzer(spot_price=spot_btc)
calls, puts, pcr = analyzer.build_options_chain(btc_options)
max_pain = analyzer.calculate_max_pain(btc_options)
6. HolySheep AI와 통합 분석
지금까지의 정량 분석 결과를 HolySheep AI의 LLM API와 결합하면 펀딩费率 및 옵션 체인 데이터를 종합적으로 해석할 수 있습니다. HolySheep AI는 단일 API 키로 GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash, DeepSeek V3.2 등 주요 모델을 모두 지원합니다.
import requests
import json
from typing import Dict, List, Any
class HolySheepAnalyzer:
"""HolySheep AI를 활용한 파생상품 분석"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.holysheep.ai/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def analyze_funding_summary(self, funding_stats: Dict, market_context: str = "") -> str:
"""펀딩费率 분석 결과를 AI로 해석"""
prompt = f"""암호화폐 펀딩费率 분석 결과를 해석해주세요.
【분석 데이터】
- 평균 펀딩费率: {funding_stats['mean']:.6f} ({funding_stats['mean']*100:.4f}%)
- 연간 환산: {funding_stats['mean']*3*365*100:.2f}%
- 표준편차: {funding_stats['std']:.6f}
- 양수 비율: {funding_stats['positive_rate']:.1f}%
【시장 맥락】
{market_context}
【분석 요청】
1. 현재 시장 과열/냉각 상태 평가
2. 향후 24시간 시장 방향성 전망
3. 리스크 경고사항 (如果有的话)
한국어로 간결하게 3문장 이내로 답변해주세요."""
payload = {
"model": "gpt-4.1",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 500,
"temperature": 0.3
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
raise Exception(f"HolySheep API 오류: {response.status_code}")
def generate_options_report(self, options_data: Dict, spot_price: float,
max_pain: float) -> str:
"""옵션 체인 보고서 생성"""
prompt = f"""BTC 옵션 체인 분석 보고서를 작성해주세요.
【현물 가격】${spot_price:,.0f}
【맥스페인】${max_pain:,.0f}
【PCR】{options_data['pcr']:.3f}
【Calls (상위 5개 스트라이크)】
{self._format_options_table(options_data['calls'])}
【Puts (상위 5개 스트라이크)】
{self._format_options_table(options_data['puts'])}
【요청】
1. PCR 기반 시장 심리 해석
2. 맥스페인 대비 현물 위치 분석
3. 주요 저항/지지 구간 식별
4. 단기 전략 제안
한국어로 상세하게 작성해주세요."""
payload = {
"model": "claude-sonnet-4.5",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 1000,
"temperature": 0.4
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload
)
return response.json()['choices'][0]['message']['content']
def _format_options_table(self, df: pd.DataFrame) -> str:
"""옵션 테이블 포맷팅"""
top5 = df.nlargest(5, 'open_interest')
return "\n".join([
f"Strike: ${row['strike']:,.0f} | IV: {row.get('iv', 0)*100:.1f}% | OI: {row['open_interest']:,.0f}"
for _, row in top5.iterrows()
])
사용 예시
holysheep = HolySheepAnalyzer(api_key="YOUR_HOLYSHEEP_API_KEY")
펀딩费率 해석
funding_insight = holysheep.analyze_funding_summary(
funding_stats=stats,
market_context="BTC 가격 $65,000 부근 횡보, 변동성 지수(IV) 45% 수준"
)
print("【펀딩费率 AI 해석】")
print(funding_insight)
옵션 보고서 생성
options_report = holysheep.generate_options_report(
options_data={'calls': calls, 'puts': puts, 'pcr': pcr},
spot_price=spot_btc,
max_pain=max_pain
)
print("\n【옵션 체인 보고서】")
print(options_report)
7. HolySheep AI 모델 비용 비교
파생상품 분석 워크플로우에서 HolySheep AI를 활용하면 다양한 모델을 상황에 맞게 선택할 수 있습니다. 월 1,000만 토큰 기준 비용을 비교하면 다음과 같습니다:
| 모델 | 입력 비용 | 출력 비용 | 월 1,000만 토큰 비용 | 적합 용도 |
|---|---|---|---|---|
| DeepSeek V3.2 | $0.42/MTok | $0.42/MTok | 약 $4.20 | 대량 데이터 처리, 기본 분석 |
| Gemini 2.5 Flash | $2.50/MTok | $2.50/MTok | 약 $25 | 빠른 요약, 실시간 분석 |
| GPT-4.1 | $8/MTok | $8/MTok | 약 $80 | 복잡한 분석, 상세 보고서 |
| Claude Sonnet 4.5 | $15/MTok | $15/MTok | 약 $150 | 고급 인사이트, 장기 예측 |
8. 통합 대시보드 구축
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from datetime import datetime
class DerivativeDashboard:
"""파생상품 분석 대시보드"""
def __init__(self, holysheep_analyzer: HolySheepAnalyzer):
self.analyzer = holysheep_analyzer
def create_combined_dashboard(self, funding_df: pd.DataFrame,
options_df: pd.DataFrame,
spot_price: float) -> go.Figure:
"""통합 대시보드 생성"""
fig = make_subplots(
rows=3, cols=2,
specs=[[{"colspan": 2}, None],
[{"type": "bar"}, {"type": "pie"}],
[{"colspan": 2}, None]],
subplot_titles=(
"펀딩费率 시계열",
"콜 옵션 OI 분포", "풋 옵션 OI 분포",
"AI 시장 해석"
),
row_heights=[0.4, 0.3, 0.3],
vertical_spacing=0.12,
horizontal_spacing=0.1
)
# 1. 펀딩费率 시계열
fig.add_trace(
go.Scatter(
x=funding_df['timestamp'],
y=funding_df['funding_rate'] * 100,
mode='lines',
name='펀딩费率',
line=dict(color='#0066ff', width=1.5)
),
row=1, col=1
)
fig.add_hline(y=0, line_dash="dash", line_color="red", row=1, col=1)
# 2. 콜 옵션 OI
calls_sorted = options_df[options_df['option_type'] == 'call'].nlargest(10, 'open_interest')
fig.add_trace(
go.Bar(
x=calls_sorted['strike'],
y=calls_sorted['open_interest'],
name='콜 OI',
marker_color='#00cc66'
),
row=2, col=1
)
# 3. 풋 옵션 OI
puts_sorted = options_df[options_df['option_type'] == 'put'].nlargest(10, 'open_interest')
fig.add_trace(
go.Bar(
x=puts_sorted['strike'],
y=puts_sorted['open_interest'],
name='풋 OI',
marker_color='#ff6666'
),
row=2, col=2
)
# 레이아웃 업데이트
fig.update_layout(
height=900,
title_text=f"암호화폐 파생상품 분석 대시보드 (Spot: ${spot_price:,.0f})",
showlegend=True,
template="plotly_dark"
)
# AI 해석 텍스트 (실제로는 HolySheep API 호출)
ai_text = f"""
【펀딩분석】
평균: {funding_df['funding_rate'].mean()*100:.4f}% (8h)
양수비율: {(funding_df['funding_rate'] > 0).mean()*100:.1f}%
【옵션분석】
PCR: {pcr:.3f}
시장심리: {'약세' if pcr > 1 else '강세'}
【결론】
현재 시장 Conditions 분석 필요
"""
fig.add_annotation(
text=ai_text,
xref="x domain", yref="y domain",
x=0.5, y=0.05,
showarrow=False,
font=dict(size=12),
bgcolor="rgba(0,0,0,0.8)",
bordercolor="white",
borderwidth=1,
align="left"
)
return fig
대시보드 실행
dashboard = DerivativeDashboard(holysheep)
fig = dashboard.create_combined_dashboard(btc_funding, btc_options, spot_btc)
fig.show()
fig.write_html("./outputs/derivative_dashboard.html")
이런 팀에 적합 / 비적격
| ✅ 적합한 팀 | ❌ 비적합한 팀 |
|---|---|
|
퀀트 트레이딩 팀 Tardis 데이터 기반 알파 전략 개발 고빈도 펀딩费率 차익거래 |
단순 바이앤홀드 투자자 파생상품 분석 필요 없는 팀 로우데이터 기반 결정 선호 |
|
리스크 관리 부서 옵션 포지션 델타/감마 헷징 펀딩비용 기반 리스크 계산 |
초소규모 개인 트레이더 API 비용이 수익을上회하는 경우 전문 분석 인프라 미구축 |
|
헤지펀드 / VC 시장 구조 분석 및 진입时机 포착 다중 거래소 데이터 통합 분석 |
규제 준수 중심 기관 단순 지수 추적 목적 복잡한 파생상품 거래 금지 |
가격과 ROI
HolySheep AI를 파생상품 분석 워크플로우에 활용할 때의 비용 효율성을 분석해 보겠습니다.
| 시나리오 | 월간 토큰 사용량 | DeepSeek V3.2 | Gemini 2.5 Flash | GPT-4.1 | Claude Sonnet 4.5 |
|---|---|---|---|---|---|
| 개인 트레이더 (기본) | 100만 토큰 | $0.42 | $2.50 | $8 | $15 |
| 중소팀 (일상적 분석) | 1,000만 토큰 | $4.20 | $25 | $80 | $150 |
| 헤지펀드 (고강도 분석) | 1억 토큰 | $42 | $250 | $800 | $1,500 |
ROI 관점: 월 $25 수준의 Gemini 2.5 Flash 플랜으로 일일 100회 옵션 보고서 생성 시, 수동 분석 대비 약 40시간의 노동을 절약할 수 있습니다. 전문 애널리스트 시간당 $100 기준으로 월 $4,000 상당의 가치를 창출합니다.
왜 HolySheep를 선택해야 하나
- 단일 API로 모든 모델 통합: DeepSeek V3.2 ($0.42/MTok)에서 Claude Sonnet 4.5 ($15/MTok)까지, 분석 목적에 따라 유연하게 모델을 전환할 수 있습니다.
- 비용 최적화: 기본 분석은 DeepSeek V3.2로 처리하고, 핵심 인사이트에만 Claude Sonnet 4.5를 사용하는 하이브리드 전략으로 비용을 70% 절감할 수 있습니다.
- 해외 신용카드 불필요: HolySheep는 로컬 결제 시스템을 지원하여, 글로벌 결제 어려움 없이 즉시 가입하고 API를 활용할 수 있습니다.
- 신뢰할 수 있는 연결: HolySheep AI 게이트웨이는 안정적인 연결과 빠른 응답 속도를 제공하여, 실시간 시장 분석에 적합합니다.
- 무료 크레딧 제공: 지금 가입하면 무료 크레딧을 받을 수 있어, 첫 달 비용 부담 없이 분석 워크플로우를 구축할 수 있습니다.
자주 발생하는 오류와 해결책
오류 1: Tardis CSV 파일 로드 실패
# 오류 메시지
FileNotFoundError: [Errno 2] No such file or directory: './data/funding_rates/...'
해결책
import os
from pathlib import Path
경로 확인 및 자동 생성
data_dir = Path('./data')
(data_dir / 'funding_rates').mkdir(parents=True, exist_ok=True)
(data_dir / 'options').mkdir(parents=True, exist_ok=True)
Tardis에서 데이터 다운로드
https://docs.tardis.dev 에서 API 키 발급 후
import tarfile
def download_tardis_data(exchange, symbol, data_type, year, month):
"""Tardis 데이터 자동 다운로드"""
base_url = "https://api.tardis.dev/v1/download"
# 실제 API 키로 교체 필요
# response = requests.get(f"{base_url}?exchange={exchange}&symbol={symbol}...")
pass
또는 로컬 경로 명시적 지정
loader = TardisDataLoader(data_dir='/absolute/path/to/data')
오류 2: HolySheep API 인증 실패
# 오류 메시지
{"error": {"message": "Invalid API key", "type": "invalid_request_error"}}
해결책
import os
환경변수에서 API 키 로드 (권장)
api_key = os.environ.get('HOLYSHEEP_API_KEY')
if not api_key:
# 직접 입력 (테스트용)
api_key = "YOUR_HOLYSHEEP_API_KEY"
키 형식 검증
if not api_key or len(api_key) < 20:
raise ValueError("유효한 HolySheep API 키를 설정해주세요.")
올바른 엔드포인트 사용
BASE_URL = "https://api.holysheep.ai/v1" # 절대 수정 금지
테스트 요청
response = requests.get(
f"{BASE_URL}/models",
headers={"Authorization": f"Bearer {api_key}"}
)
if response.status_code == 401:
raise Exception("API 키가 만료되었거나無効되었습니다. 대시보드에서 확인해주세요.")
오류 3: 옵션 IV(내재변동성) 데이터 누락
# 오류 메시지
KeyError: 'iv' 또는 NaN 값 포함
해결책
def handle_missing_iv(options_df):
"""IV 데이터 결측치 처리"""
if 'iv' not in options_df.columns:
# Bid-Ask 중간값으로 IV 추정
if 'bid' in options_df.columns and 'ask' in options_df.columns:
mid_price = (options_df['bid'] + options_df['ask']) / 2
options_df['iv'] = estimate_iv_from_price(
spot=options_df['spot'],
strike=options_df['strike'],
time=options_df['time_to_expiry'],
price=mid_price,
option_type=options_df['option_type']
)
else:
options_df['iv'] = 0.5 # 기본값 50% IV
# NaN 대체
options_df['iv'] = options_df['iv'].fillna(0.5)
options_df['iv'] = options_df['iv'].replace(0, 0.5)
return options_df
def estimate_iv_from_price(spot, strike, time, price, option_type):
"""단순 IV 추정 (Newton-Raphson)"""
from scipy.optimize import brentq
def bs_price(iv):
d1 = (np.log(spot/strike) + 0.5*iv**2*time) / (iv*np.sqrt(time))
d2 = d1 - iv*np.sqrt(time)
if option_type == 'call':
return spot*norm.cdf(d1) - strike*np.exp(-0.05*time)*norm.cdf(d2) - price
else:
return strike*np.exp(-0.05*time)*norm.cdf(-d2) - spot*norm.cdf(-d1) - price
try:
return brentq(bs_price