第12章:风险管理与资金管理
> 控制风险是量化交易生存的关键。
学习目标
- ✅ 理解风险管理的重要性
- ✅ 掌握仓位管理方法
- ✅ 实现止损止盈策略
- ✅ 计算VaR和CVaR
12.1 风险类型
主要风险
1. 市场风险:价格波动 2. 流动性风险:买卖困难 3. 操作风险:系统故障 4. 模型风险:策略失效
12.2 仓位管理
凯利公式
def kelly_criterion(win_rate, win_loss_ratio):
"""
凯利公式:计算最优仓位
f* = (p * b - q) / b
p: 胜率
q: 败率
b: 盈亏比
"""
p = win_rate
q = 1 - win_rate
b = win_loss_ratio
kelly = (p * b - q) / b
# 实际使用半凯利(更保守)
return max(0, kelly * 0.5)
# 使用示例
position = kelly_criterion(win_rate=0.6, win_loss_ratio=2.0)
print(f"建议仓位:{position:.2%}") # 约20%
波动率目标
class VolatilityTargetPosition:
"""波动率目标仓位管理"""
def __init__(self, target_vol=0.15):
self.target_vol = target_vol
def calculate_position(self, returns):
"""计算仓位"""
current_vol = returns.rolling(20).std() * np.sqrt(252)
position = self.target_vol / current_vol
return min(position, 1.0) # 最大100%仓位
等风险贡献
def risk_parity_weights(returns):
"""风险平价权重"""
cov_matrix = returns.cov() * 252
n = len(returns.columns)
def risk_contribution(weights):
portfolio_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
marginal_contrib = np.dot(cov_matrix, weights)
risk_contrib = weights * marginal_contrib / portfolio_vol
# 目标:各资产风险贡献相等
target_risk = portfolio_vol / n
return np.sum((risk_contrib - target_risk) ** 2)
# 优化求解...
12.3 止损止盈
固定比例止损
class StopLossTakeProfit:
"""止损止盈"""
def __init__(self, stop_loss=-0.05, take_profit=0.10):
self.stop_loss = stop_loss
self.take_profit = take_profit
def check(self, entry_price, current_price, position):
"""检查是否触发"""
pnl = (current_price - entry_price) / entry_price
if position > 0: # 多头
if pnl <= self.stop_loss:
return 'STOP_LOSS'
elif pnl >= self.take_profit:
return 'TAKE_PROFIT'
return None
移动止损
class TrailingStop:
"""移动止损"""
def __init__(self, trailing_percent=0.05):
self.trailing_percent = trailing_percent
self.highest_price = None
def update(self, current_price):
"""更新最高价"""
if self.highest_price is None or current_price > self.highest_price:
self.highest_price = current_price
def should_stop(self, current_price):
"""是否触发"""
if self.highest_price is None:
return False
drawdown = (current_price - self.highest_price) / self.highest_price
return drawdown <= -self.trailing_percent
12.4 VaR计算
历史模拟法
def calculate_var(returns, confidence=0.95):
"""计算VaR(历史模拟法)"""
return np.percentile(returns, (1 - confidence) * 100)
def calculate_cvar(returns, confidence=0.95):
"""计算CVaR(条件风险价值)"""
var = calculate_var(returns, confidence)
return returns[returns <= var].mean()
参数法
from scipy.stats import norm
def calculate_var_parametric(returns, confidence=0.95):
"""计算VaR(参数法)"""
mean = returns.mean()
std = returns.std()
var = norm.ppf(1 - confidence, mean, std)
return var
12.5 风险监控
class RiskMonitor:
"""风险监控"""
def __init__(self, max_drawdown=-0.10, max_var=0.05):
self.max_drawdown = max_drawdown
self.max_var = max_var
def check(self, portfolio):
"""检查风险"""
alerts = []
# 回撤检查
if portfolio.drawdown < self.max_drawdown:
alerts.append(f"回撤过大:{portfolio.drawdown:.2%}")
# VaR检查
if portfolio.var > self.max_var:
alerts.append(f"VaR过大:{portfolio.var:.2%}")
return alerts
---
*本文节选自《AI量化交易从入门到精通》第12章* *完整内容请访问代码仓:book_writing/part3_practice/part12_risk/README.md*