今天要學習對沖策略,這就像爸爸為農作物買保險一樣。還記得那年颱風來襲,隔壁叔叔因為沒保險血本無歸,而爸爸雖然產量受損,但保險理賠讓損失降到最低。對沖就是金融世界的保險策略!
對沖是一種風險管理技術,通過建立相反的部位來減少投資組合的風險:
理論上完全消除風險的對沖:
class PerfectHedge:
"""完全對沖策略"""
def __init__(self, spot_position, hedge_ratio=1.0):
self.spot_position = spot_position # 現貨部位
self.hedge_ratio = hedge_ratio # 對沖比率
self.futures_position = -spot_position * hedge_ratio
def calculate_pnl(self, spot_price_change, futures_price_change):
"""計算對沖後的損益"""
spot_pnl = self.spot_position * spot_price_change
futures_pnl = self.futures_position * futures_price_change
total_pnl = spot_pnl + futures_pnl
return {
'spot_pnl': spot_pnl,
'futures_pnl': futures_pnl,
'total_pnl': total_pnl,
'hedge_effectiveness': 1 - abs(total_pnl) / abs(spot_pnl)
}
# 示例:完全對沖
hedge = PerfectHedge(spot_position=1.0) # 持有1 BTC現貨
# 情況1:BTC上漲10%
result1 = hedge.calculate_pnl(spot_price_change=0.1, futures_price_change=0.1)
print(f"BTC上漲10%時的對沖效果: {result1}")
# 情況2:BTC下跌15%
result2 = hedge.calculate_pnl(spot_price_change=-0.15, futures_price_change=-0.15)
print(f"BTC下跌15%時的對沖效果: {result2}")
只對沖部分風險,保留一定的收益潛力:
class PartialHedge:
"""部分對沖策略"""
def __init__(self, spot_position, hedge_ratio=0.5):
self.spot_position = spot_position
self.hedge_ratio = hedge_ratio # 50%對沖
self.futures_position = -spot_position * hedge_ratio
self.net_exposure = spot_position * (1 - hedge_ratio)
def analyze_scenarios(self, price_changes):
"""分析不同價格變動情況"""
results = []
for change in price_changes:
spot_pnl = self.spot_position * change
futures_pnl = self.futures_position * change
total_pnl = spot_pnl + futures_pnl
results.append({
'price_change': f"{change:.1%}",
'unhedged_pnl': spot_pnl,
'hedged_pnl': total_pnl,
'protection_rate': (spot_pnl - total_pnl) / spot_pnl if spot_pnl != 0 else 0
})
return results
# 分析部分對沖效果
partial_hedge = PartialHedge(spot_position=10) # 持有10個單位
scenarios = partial_hedge.analyze_scenarios([-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3])
for scenario in scenarios:
print(f"價格變動 {scenario['price_change']}: "
f"無對沖損益 {scenario['unhedged_pnl']:.2f}, "
f"對沖後損益 {scenario['hedged_pnl']:.2f}")
根據市場條件調整對沖比率:
class DynamicHedge:
"""動態對沖策略"""
def __init__(self, spot_position):
self.spot_position = spot_position
self.current_hedge_ratio = 0
self.hedge_history = []
def calculate_optimal_hedge_ratio(self, volatility, correlation, risk_tolerance):
"""計算最優對沖比率"""
# 基於波動性和相關性的動態調整
base_ratio = min(volatility * 2, 1.0) # 波動性越高,對沖比率越高
# 風險承受度調整
risk_adjustment = 1 - risk_tolerance # 風險承受度低,對沖比率高
optimal_ratio = base_ratio * risk_adjustment
return min(optimal_ratio, 1.0)
def update_hedge(self, market_data):
"""更新對沖比率"""
volatility = market_data['volatility']
correlation = market_data['correlation']
risk_tolerance = market_data['risk_tolerance']
new_ratio = self.calculate_optimal_hedge_ratio(
volatility, correlation, risk_tolerance
)
# 記錄調整
self.hedge_history.append({
'timestamp': market_data['timestamp'],
'old_ratio': self.current_hedge_ratio,
'new_ratio': new_ratio,
'reason': self.get_adjustment_reason(new_ratio)
})
self.current_hedge_ratio = new_ratio
return new_ratio
def get_adjustment_reason(self, new_ratio):
"""獲取調整原因"""
if new_ratio > self.current_hedge_ratio:
return "增加對沖:市場風險上升"
elif new_ratio < self.current_hedge_ratio:
return "減少對沖:市場趨勢明確"
else:
return "維持對沖:市場狀況穩定"
class FuturesHedge:
"""期貨對沖策略"""
def __init__(self, spot_position, contract_size=1):
self.spot_position = spot_position
self.contract_size = contract_size
self.contracts_needed = spot_position / contract_size
def calculate_basis_risk(self, spot_price, futures_price):
"""計算基差風險"""
basis = futures_price - spot_price
basis_risk = abs(basis) / spot_price
return basis, basis_risk
def hedge_effectiveness(self, spot_returns, futures_returns):
"""計算對沖有效性"""
import numpy as np
# 計算對沖組合收益
hedge_returns = spot_returns - futures_returns
# 對沖有效性 = 1 - (對沖後方差 / 原始方差)
original_variance = np.var(spot_returns)
hedged_variance = np.var(hedge_returns)
effectiveness = 1 - (hedged_variance / original_variance)
return effectiveness
保護性看跌期權(Protective Put):
class ProtectivePut:
"""保護性看跌期權策略"""
def __init__(self, spot_position, strike_price, option_premium):
self.spot_position = spot_position
self.strike_price = strike_price
self.option_premium = option_premium
def calculate_payoff(self, spot_price_at_expiry):
"""計算到期損益"""
# 現貨損益
spot_pnl = self.spot_position * (spot_price_at_expiry - self.strike_price)
# 選擇權損益
option_pnl = max(self.strike_price - spot_price_at_expiry, 0) * self.spot_position
# 減去選擇權權利金
total_pnl = spot_pnl + option_pnl - self.option_premium
return {
'spot_pnl': spot_pnl,
'option_pnl': option_pnl,
'premium_cost': -self.option_premium,
'total_pnl': total_pnl,
'protected': spot_price_at_expiry < self.strike_price
}
def analyze_strategy(self, price_range):
"""分析策略在不同價格下的表現"""
results = []
for price in price_range:
payoff = self.calculate_payoff(price)
results.append({
'price': price,
'total_pnl': payoff['total_pnl'],
'protected': payoff['protected']
})
return results
# 示例:保護性看跌期權
protective_put = ProtectivePut(
spot_position=1, # 持有1個單位
strike_price=50000, # 履約價50,000
option_premium=2000 # 權利金2,000
)
# 分析不同價格情況
price_range = [40000, 45000, 50000, 55000, 60000]
results = protective_put.analyze_strategy(price_range)
for result in results:
protection_status = "受保護" if result['protected'] else "未受保護"
print(f"價格 {result['price']}: 損益 {result['total_pnl']:.0f} ({protection_status})")
class HedgeCostBenefitAnalysis:
"""對沖成本效益分析"""
def __init__(self, portfolio_value):
self.portfolio_value = portfolio_value
self.costs = {
'transaction_costs': 0.001, # 0.1%交易成本
'option_premium': 0.02, # 2%選擇權權利金
'opportunity_cost': 0.05, # 5%機會成本
'basis_risk': 0.005 # 0.5%基差風險
}
def calculate_total_hedging_cost(self, hedge_ratio, time_period):
"""計算總對沖成本"""
hedged_amount = self.portfolio_value * hedge_ratio
# 直接成本
transaction_cost = hedged_amount * self.costs['transaction_costs']
premium_cost = hedged_amount * self.costs['option_premium']
# 時間相關成本
opportunity_cost = hedged_amount * self.costs['opportunity_cost'] * time_period
basis_risk_cost = hedged_amount * self.costs['basis_risk'] * time_period
total_cost = transaction_cost + premium_cost + opportunity_cost + basis_risk_cost
return {
'transaction_cost': transaction_cost,
'premium_cost': premium_cost,
'opportunity_cost': opportunity_cost,
'basis_risk_cost': basis_risk_cost,
'total_cost': total_cost,
'cost_percentage': total_cost / self.portfolio_value
}
def hedge_efficiency_ratio(self, risk_reduction, total_cost):
"""計算對沖效率比率"""
return risk_reduction / total_cost
# 成本效益分析示例
analyzer = HedgeCostBenefitAnalysis(portfolio_value=100000)
# 分析不同對沖比率的成本
hedge_ratios = [0.25, 0.5, 0.75, 1.0]
time_period = 0.25 # 3個月
for ratio in hedge_ratios:
cost_analysis = analyzer.calculate_total_hedging_cost(ratio, time_period)
print(f"對沖比率 {ratio:.0%}: 總成本 ${cost_analysis['total_cost']:.0f} "
f"({cost_analysis['cost_percentage']:.2%})")
現貨和期貨價格差異變動的風險:
def analyze_basis_risk(spot_prices, futures_prices):
"""分析基差風險"""
import numpy as np
basis = futures_prices - spot_prices
basis_volatility = np.std(basis)
basis_mean = np.mean(basis)
# 基差風險指標
basis_risk_metrics = {
'basis_volatility': basis_volatility,
'basis_mean': basis_mean,
'basis_range': [np.min(basis), np.max(basis)],
'basis_stability': 1 - (basis_volatility / abs(basis_mean)) if basis_mean != 0 else 0
}
return basis_risk_metrics
對沖比率過高導致的風險:
class CryptoPortfolioHedge:
"""加密貨幣投資組合對沖"""
def __init__(self, portfolio):
self.portfolio = portfolio # {'BTC': 2, 'ETH': 10, 'USDT': 50000}
self.hedge_positions = {}
def calculate_portfolio_beta(self, market_returns, portfolio_returns):
"""計算投資組合相對於市場的貝塔值"""
import numpy as np
covariance = np.cov(portfolio_returns, market_returns)[0][1]
market_variance = np.var(market_returns)
beta = covariance / market_variance
return beta
def implement_beta_hedge(self, beta, market_index_price):
"""實施貝塔對沖"""
# 計算投資組合總值
portfolio_value = self.calculate_portfolio_value()
# 計算對沖數量
hedge_amount = portfolio_value * beta
# 建立對沖部位(做空市場指數)
self.hedge_positions['market_hedge'] = {
'type': 'short',
'amount': hedge_amount,
'price': market_index_price,
'purpose': 'beta_hedge'
}
return hedge_amount
def calculate_portfolio_value(self):
"""計算投資組合總值(簡化)"""
# 簡化計算,實際應該獲取實時價格
return 100000 # 假設總值10萬
def rebalance_hedge(self, new_beta):
"""重新平衡對沖比率"""
current_hedge = self.hedge_positions.get('market_hedge', {}).get('amount', 0)
portfolio_value = self.calculate_portfolio_value()
target_hedge = portfolio_value * new_beta
adjustment = target_hedge - current_hedge
return {
'current_hedge': current_hedge,
'target_hedge': target_hedge,
'adjustment_needed': adjustment,
'action': 'increase_hedge' if adjustment > 0 else 'decrease_hedge'
}
class HedgePerformanceMetrics:
"""對沖策略績效指標"""
def __init__(self, unhedged_returns, hedged_returns):
self.unhedged_returns = unhedged_returns
self.hedged_returns = hedged_returns
def calculate_hedge_effectiveness(self):
"""計算對沖有效性"""
import numpy as np
unhedged_volatility = np.std(self.unhedged_returns)
hedged_volatility = np.std(self.hedged_returns)
variance_reduction = 1 - (hedged_volatility ** 2) / (unhedged_volatility ** 2)
return variance_reduction
def calculate_downside_protection(self):
"""計算下行保護效果"""
import numpy as np
unhedged_downside = np.mean([r for r in self.unhedged_returns if r < 0])
hedged_downside = np.mean([r for r in self.hedged_returns if r < 0])
if unhedged_downside == 0:
return 0
protection_ratio = 1 - abs(hedged_downside) / abs(unhedged_downside)
return protection_ratio
def calculate_upside_capture(self):
"""計算上行捕獲率"""
import numpy as np
unhedged_upside = np.mean([r for r in self.unhedged_returns if r > 0])
hedged_upside = np.mean([r for r in self.hedged_returns if r > 0])
if unhedged_upside == 0:
return 0
capture_ratio = hedged_upside / unhedged_upside
return capture_ratio
今天我們深入探討了對沖策略,就像學會了為農作物買保險的各種方法。對沖的關鍵要點:
對沖的價值:
對沖的成本:
成功對沖的關鍵:
實戰建議:
明天我們將探討虛擬貨幣中的現貨與期貨,了解這兩種工具的特性和應用!
下一篇:Day 20 - 虛擬貨幣中的現貨與期貨