Quant Risk Dashboard
Professional risk management system for quantitative trading.
Features
1. Risk Metrics
- - VaR (Value at Risk): Historical, Parametric, Monte Carlo
- CVaR (Conditional VaR): Expected shortfall
- Max Drawdown: Current and historical
- Volatility: Realized and implied
- Beta: Market sensitivity
- Sharpe/Sortino/Calar: Risk-adjusted returns
2. Position Management
- - Real-time Positions: Current holdings with P&L
- Position Limits: Per-stock and total limits
- Concentration Risk: Single position max%
- Sector Exposure: Industry allocation
3. Exposure Monitoring
- - Long/Short Ratio: Net exposure
- Sector Allocation: Industry breakdown
- Factor Exposure: Style factors (value, growth, momentum)
- Geographic Exposure: Market cap breakdown
4. Stress Testing
- - Historical Scenarios: 2008 crash, 2020 covid, etc.
- Custom Scenarios: User-defined shocks
- Scenario Comparison: Side-by-side analysis
- Recovery Time: Estimated recovery from scenarios
5. Alerts & Notifications
- - Drawdown Alerts: Threshold-based warnings
- Position Breach: Limit violation alerts
- Volatility Spikes: Unusual market moves
- Custom Rules: User-defined triggers
6. Reporting
- - Daily Risk Report: Automated PDF/HTML reports
- Risk Attribution: P&L explained by factors
- Compliance Reports: Regulatory compliance
- Custom Reports: Flexible report builder
Installation
CODEBLOCK0
Usage
Initialize Dashboard
CODEBLOCK1
Add Positions
CODEBLOCK2
Get Risk Metrics
CODEBLOCK3
Stress Test
CODEBLOCK4
Start Web Dashboard
CODEBLOCK5
API Reference
Core Methods
| Method | Description |
|---|
| INLINECODE0 | Add position |
| INLINECODE1 |
Close position |
|
update_price(symbol, price) | Update market price |
|
get_positions() | Get all positions |
|
get_risk_metrics() | Calculate risk metrics |
Risk Analysis
| Method | Description |
|---|
| INLINECODE5 | Calculate VaR |
| INLINECODE6 |
Calculate CVaR |
|
stress_test(scenarios) | Run stress tests |
|
factor_exposure() | Calculate factor exposure |
|
sector_allocation() | Get sector breakdown |
Alerts
| Method | Description |
|---|
| INLINECODE10 | Create alert |
| INLINECODE11 |
Get active alerts |
|
clear_alerts() | Clear alerts |
Reports
| Method | Description |
|---|
| INLINECODE13 | Generate report |
| INLINECODE14 |
Daily summary |
Risk Metrics Explained
VaR (Value at Risk)
- - Definition: Maximum expected loss at given confidence level
- Interpretation: "95% VaR = 50,000" means 95% chance loss < 50,000
CVaR (Conditional VaR)
- - Definition: Average loss beyond VaR threshold
- Interpretation: More conservative than VaR
Sharpe Ratio
- - Definition: Risk-adjusted return
- Interpretation: >1.0 good, >2.0 excellent
Max Drawdown
- - Definition: Largest peak-to-trough decline
- Interpretation: Lower is better
Sortino Ratio
- - Definition: Downside risk-adjusted return
- Interpretation: Only considers downside risk
Configuration
Risk Limits
CODEBLOCK6
Alert Thresholds
CODEBLOCK7
Visualization
Web Dashboard
CODEBLOCK8
Generate Charts
CODEBLOCK9
Integration
Connect to Trading System
CODEBLOCK10
Webhook Alerts
CODEBLOCK11
Use Cases
- - Live Trading: Real-time risk monitoring
- Backtesting: Post-trade risk analysis
- Portfolio Management: Multi-strategy risk
- Compliance: Regulatory risk reports
- Risk Research: Strategy risk profiling
Links
量化风险仪表盘
专业量化交易风险管理系统。
功能特性
1. 风险指标
- - VaR(风险价值):历史法、参数法、蒙特卡洛法
- CVaR(条件风险价值):预期亏损
- 最大回撤:当前及历史回撤
- 波动率:已实现波动率与隐含波动率
- Beta系数:市场敏感性
- 夏普/索提诺/卡玛比率:风险调整后收益
2. 持仓管理
- - 实时持仓:当前持仓及盈亏
- 持仓限额:个股限额与总限额
- 集中度风险:单只持仓最大占比
- 行业敞口:行业配置分布
3. 敞口监控
- - 多空比率:净敞口
- 行业配置:行业分布明细
- 因子敞口:风格因子(价值、成长、动量)
- 地域敞口:市值分布明细
4. 压力测试
- - 历史情景:2008年崩盘、2020年新冠疫情等
- 自定义情景:用户自定义冲击
- 情景对比:并排分析
- 恢复时间:情景恢复预估时间
5. 预警与通知
- - 回撤预警:基于阈值的警告
- 持仓违规:限额违规警报
- 波动率飙升:异常市场波动
- 自定义规则:用户自定义触发条件
6. 报告生成
- - 每日风险报告:自动生成PDF/HTML报告
- 风险归因:按因子分解盈亏
- 合规报告:监管合规报告
- 自定义报告:灵活的报告生成器
安装
bash
pip install pandas numpy scipy plotly dash
使用说明
初始化仪表盘
python
from quant_risk import RiskDashboard
dashboard = RiskDashboard(
initial_capital=1000000,
var_confidence=0.95,
maxpositionpct=0.15,
maxdrawdownpct=0.20
)
添加持仓
python
dashboard.add_position(
symbol=600519,
shares=1000,
entry_price=1800.0,
current_price=1850.0
)
dashboard.add_position(
symbol=000858,
shares=5000,
entry_price=45.0,
current_price=48.0
)
获取风险指标
python
metrics = dashboard.get
riskmetrics()
print(fVaR (95%): {metrics[var_95]:,.2f})
print(fCVaR (95%): {metrics[cvar_95]:,.2f})
print(f夏普比率: {metrics[sharpe_ratio]:.2f})
print(f最大回撤: {metrics[max_drawdown]:.2%})
print(f总敞口: {metrics[total_exposure]:,.0f})
压力测试
python
scenarios = {
2008年崩盘: -0.50,
2020年新冠疫情: -0.30,
加息冲击: -0.15,
自定义情景: -0.25
}
results = dashboard.stress_test(scenarios)
for name, result in results.items():
print(f{name}: 盈亏 = {result[pnl]:,.2f})
启动网页仪表盘
python
dashboard.start_dashboard(port=8050)
打开 http://localhost:8050
API参考
核心方法
| 方法 | 描述 |
|---|
| addposition(symbol, shares, entry, current) | 添加持仓 |
| removeposition(symbol) |
平仓 |
| update_price(symbol, price) | 更新市场价格 |
| get_positions() | 获取所有持仓 |
| get
riskmetrics() | 计算风险指标 |
风险分析
| 方法 | 描述 |
|---|
| calculatevar(method=historical) | 计算VaR |
| calculatecvar() |
计算CVaR |
| stress_test(scenarios) | 运行压力测试 |
| factor_exposure() | 计算因子敞口 |
| sector_allocation() | 获取行业分布 |
预警
| 方法 | 描述 |
|---|
| addalert(condition, message) | 创建预警 |
| getalerts() |
获取活跃预警 |
| clear_alerts() | 清除预警 |
报告
| 方法 | 描述 |
|---|
| generatereport(format=pdf) | 生成报告 |
| getdaily_summary() |
每日摘要 |
风险指标详解
VaR(风险价值)
- - 定义:给定置信水平下的最大预期损失
- 解读:95% VaR = 50,000 表示95%的概率损失不超过50,000
CVaR(条件风险价值)
- - 定义:超过VaR阈值的平均损失
- 解读:比VaR更为保守
夏普比率
- - 定义:风险调整后收益
- 解读:>1.0良好,>2.0优秀
最大回撤
索提诺比率
配置参数
风险限额
python
limits = {
max
positionpct: 0.15, # 单只持仓15%
max
sectorpct: 0.30, # 单个行业30%
max_leverage: 1.5, # 1.5倍杠杆
max_drawdown: 0.20, # 20%止损
max
varpct: 0.05, # 5% VaR限额
}
预警阈值
python
alerts = {
drawdown_warning: 0.10, # 10%回撤警告
drawdown_critical: 0.15, # 15%严重警告
var_warning: 0.03, # 3% VaR警告
volatility_spike: 2.0, # 2倍正常波动率
}
可视化
网页仪表盘
python
dashboard.start_dashboard()
功能:
- 实时持仓表格
- 盈亏图表
- 风险指标仪表盘
- 行业饼图
- 回撤曲线
- 因子敞口柱状图
生成图表
python
盈亏图表
chart = dashboard.plot
pnlhistory()
风险分解
chart = dashboard.plot
riskattribution()
情景对比
chart = dashboard.plot_scenarios()
集成对接
连接交易系统
python
从交易系统接入
import asyncio
async def update_positions():
while True:
positions = await tradingsystem.getpositions()
for pos in positions:
dashboard.updateprice(pos.symbol, pos.currentprice)
await asyncio.sleep(60) # 每分钟更新一次
asyncio.run(update_positions())
Webhook预警
python
发送预警到Slack/微信
def on_alert(alert):
send_webhook(
url=os.getenv(ALERT_WEBHOOK),
message=f风险预警: {alert[message]}
)
dashboard.setalertcallback(on_alert)
应用场景
- - 实盘交易:实时风险监控
- 回测分析:交易后风险分析
- 投资组合管理:多策略风险管理
- 合规监管:监管风险报告
- 风险研究:策略风险画像
相关链接