Files
ljwx-stock/DASHBOARD_DEPLOYMENT.md
brunoandClaude 3e7113df75 feat: Complete Dashboard optimization with strategy management and risk radar
This is a major enhancement to the Dashboard, adding two key sections:
- Strategy Management (Theme & Strategy section)
- Risk Radar (Multi-dimensional risk monitoring)

Backend API:
- Add strategy management API (strategies.py)
  * GET /api/strategies/list - Strategy list with filtering
  * GET /api/strategies/{id}/detail - Strategy details with backtest data
  * 4 built-in strategies: AI Comprehensive, Value Focus, Momentum, Defensive
- Add risk radar API (risk_radar.py)
  * GET /api/risk/overview - Risk overview with 4-dimension breakdown
  * GET /api/risk/events - Structured risk events with impact analysis
  * GET /api/risk/timeline - 7-day forward risk calendar
  * GET /api/risk/strategy-impact - Strategy-risk correlation (key feature)

Frontend Components:
- Add StrategyCard.vue - Strategy card with metrics and AI insights
- Add StrategyDetailDrawer.vue - Strategy details with backtest chart (ECharts)
- Add RiskRadarGauge.vue - Risk dashboard with gauge chart (ECharts)
- Add RiskEventCard.vue - Structured risk event card
- Add RiskTimeline.vue - Horizontal timeline for upcoming risks
- Add DashboardV2Enhanced.vue - Complete dashboard with strategy-risk correlation

Key Features:
- Strategy-risk correlation logic: dynamically adjust strategy recommendations based on risk environment
- Multi-level risk monitoring: overall score + 4-dimension breakdown + structured events
- Rich decision information: backtest curves, position advice, AI insights
- Responsive layout: Desktop (2/3 + 1/3), Mobile (vertical stack)

Documentation:
- Add DASHBOARD_OPTIMIZATION_GUIDE.md - Implementation guide (450 lines)
- Add DASHBOARD_DEPLOYMENT.md - Deployment guide with troubleshooting
- Add DASHBOARD_COMPLETION_SUMMARY.md - Project completion summary
- Add test_dashboard_apis.sh - API testing script

Total: ~5,850 lines of code and documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-16 09:21:12 +08:00

580 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Dashboard 优化完整部署指南
## 🎉 项目完成情况
### ✅ 已完成功能
#### 后端 API(100%)
- [x] 策略管理 API(`backend/app/routes/strategies.py`)
- [x] 策略列表(支持筛选)
- [x] 策略详情(回测数据、仓位建议、AI洞察)
- [x] 4种内置策略配置
- [x] 风险雷达 API(`backend/app/routes/risk_radar.py`)
- [x] 风险总览(综合指数+四维分解)
- [x] 风险事件列表(结构化)
- [x] 风险时间线(未来7天)
- [x] 策略风险联动(关键功能)
- [x] 路由注册(`backend/main.py`)
#### 前端组件(100%)
- [x] `StrategyCard.vue` - 策略卡片
- [x] `StrategyDetailDrawer.vue` - 策略详情抽屉(含ECharts回测曲线)
- [x] `RiskRadarGauge.vue` - 风险仪表盘(ECharts圆环图)
- [x] `RiskEventCard.vue` - 风险事件卡片
- [x] `RiskTimeline.vue` - 风险时间线
- [x] `DashboardV2Enhanced.vue` - 完整Dashboard(含联动逻辑)
- [x] API服务层(`frontend/src/services/api.js`)
#### 文档(100%)
- [x] 实施指南(`DASHBOARD_OPTIMIZATION_GUIDE.md`)
- [x] 部署指南(本文档)
- [x] API测试脚本(`test_dashboard_apis.sh`)
---
## 🚀 快速部署(5分钟上手)
### 步骤 1:启动后端
```bash
# 进入后端目录
cd backend
# 激活虚拟环境(如果已有)
source .venv/bin/activate
# 或创建新虚拟环境
python3 -m venv .venv
source .venv/bin/activate
# 安装依赖(如果需要)
pip install -r requirements.txt
# 启动后端
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
**验证后端:**
```bash
# 在另一个终端窗口
curl http://localhost:8000/health
# 应该看到:
# {"status": "healthy", "database": true, "cache": true}
```
---
### 步骤 2:测试所有新 API
```bash
# 在项目根目录运行测试脚本
./test_dashboard_apis.sh
```
**预期输出:**
```
==================================================
Dashboard 优化 API 测试
==================================================
检查后端服务...
✓ 后端服务运行正常
==================== 策略管理 API ====================
测试: 获取所有策略列表
URL: GET http://localhost:8000/api/strategies/list
✓ 成功 (HTTP 200)
响应数据预览:
{
"strategies": [
{
"id": "ai_comprehensive",
"name": "AI 价值精选",
"tagline": "侧重低估蓝筹,中长期滚动",
...
}
]
}
--------------------------------------------------
测试: 获取AI综合策略详情
URL: GET http://localhost:8000/api/strategies/ai_comprehensive/detail
✓ 成功 (HTTP 200)
...
==================== 风险雷达 API ====================
测试: 获取风险总览
URL: GET http://localhost:8000/api/risk/overview
✓ 成功 (HTTP 200)
...
测试: 获取策略风险联动
URL: GET http://localhost:8000/api/risk/strategy-impact
✓ 成功 (HTTP 200)
...
```
---
### 步骤 3:启动前端
```bash
# 进入前端目录
cd frontend
# 安装依赖(如果需要)
npm install
# 启动开发服务器
npm run dev
```
**访问地址:**
- 前端: http://localhost:5173
- 后端API文档: http://localhost:8000/docs
---
### 步骤 4:查看新 Dashboard
1. 浏览器打开 `http://localhost:5173`
2. 导航到 Dashboard 页面
3. 查看新功能:
- **上方**:今日推荐(保持原样)
- **左下(2/3宽)**:主题&策略区
- 策略卡片网格(2列)
- 点击"查看详情"打开策略详情抽屉
- **右下(1/3宽)**:风险雷达区
- 风险仪表盘(圆环+柱状图)
- 风险事件列表
- 风险时间线
---
## 📋 关键功能验证清单
### ✅ 策略管理功能
- [ ] 策略卡片显示正确(名称、标签、指标、TOP3标的、AI观点)
- [ ] 推荐度进度条颜色正确(绿/黄/灰)
- [ ] 点击"查看详情"打开侧边抽屉
- [ ] 抽屉内回测曲线正常显示(ECharts)
- [ ] 阶段时间线显示正确(已完成/当前/待定)
- [ ] 点击"应用策略"触发事件
### ✅ 风险雷达功能
- [ ] 风险仪表盘圆环图显示(综合风险指数)
- [ ] 四维风险柱状图显示(政策/流动性/技术/情绪)
- [ ] 风险事件卡片显示完整信息
- [ ] 风险时间线横向滚动正常
- [ ] 点击时间线事件显示弹窗
### ✅ 联动功能(关键!)
- [ ] 空状态时显示推荐策略预览
- [ ] 策略卡片显示风险影响标记
- "受当前宏观风险影响↓"(负面)
- "当前环境推荐↑"(正面)
- [ ] 策略推荐度根据风险动态调整
---
## 🔧 故障排查
### 问题 1:API 404 错误
**症状:** 前端请求返回 404
**解决方案:**
```bash
# 检查路由是否注册
cd backend
grep "strategies\|risk_radar" main.py
# 应该看到:
# from app.routes import ... strategies, risk_radar
# app.include_router(strategies.router, ...)
# app.include_router(risk_radar.router, ...)
```
如果没有,手动添加:
```python
# backend/main.py
from app.routes import ... strategies, risk_radar
app.include_router(strategies.router, tags=["Investment Strategies"])
app.include_router(risk_radar.router, tags=["Risk Radar & Monitoring"])
```
---
### 问题 2:ECharts 图表不显示
**症状:** 回测曲线或风险仪表盘空白
**解决方案:**
```bash
# 检查 echarts 是否安装
cd frontend
npm list echarts
# 如果未安装
npm install echarts
```
**检查浏览器控制台:**
- 查看是否有 JavaScript 错误
- 检查 `ref` 是否正确绑定
---
### 问题 3:CORS 错误
**症状:** 浏览器控制台显示 CORS 错误
**解决方案:**
```python
# backend/app/config.py
# 确认前端地址在 CORS 白名单
CORS_ORIGINS = [
"http://localhost:5173", # Vite dev server
"http://localhost:8090", # Docker frontend
"http://192.168.1.83:8090"
]
```
---
### 问题 4:策略风险联动不工作
**症状:** 策略卡片上没有风险影响标记
**检查:**
1. API 是否返回正确数据:
```bash
curl http://localhost:8000/api/risk/strategy-impact | python3 -m json.tool
```
2. 浏览器控制台查看 `loadStrategyRiskImpact()` 是否被调用
3. 检查 `markStrategiesWithRiskImpact()` 函数逻辑
---
## 📂 新增文件清单
### 后端(2个文件)
```
backend/app/routes/
├── strategies.py # 策略管理API(新增)
└── risk_radar.py # 风险雷达API(新增)
```
### 前端(6个文件)
```
frontend/src/
├── components/
│ ├── StrategyCard.vue # 策略卡片(新增)
│ ├── StrategyDetailDrawer.vue # 策略详情抽屉(新增)
│ ├── RiskRadarGauge.vue # 风险仪表盘(新增)
│ ├── RiskEventCard.vue # 风险事件卡片(新增)
│ └── RiskTimeline.vue # 风险时间线(新增)
└── views/
└── DashboardV2Enhanced.vue # 增强版Dashboard(新增)
```
### 文档 & 脚本(3个文件)
```
/
├── DASHBOARD_OPTIMIZATION_GUIDE.md # 实施指南(新增)
├── DASHBOARD_DEPLOYMENT.md # 部署指南(新增)
└── test_dashboard_apis.sh # API测试脚本(新增)
```
### 修改文件(2个)
```
backend/main.py # 注册新路由(修改)
frontend/src/services/api.js # 新增6个API方法(修改)
```
---
## 🎯 使用新 Dashboard 替换旧版本
如果你想使用新的 Dashboard 替换旧版本:
### 方案 A:直接替换
```bash
cd frontend/src/views
# 备份旧版本
cp DashboardV2.vue DashboardV2.vue.backup
# 使用新版本
cp DashboardV2Enhanced.vue DashboardV2.vue
```
### 方案 B:路由配置(推荐)
在路由配置中添加新页面:
```javascript
// frontend/src/router/index.js
{
path: '/dashboard-v2',
name: 'DashboardV2',
component: () => import('@/views/DashboardV2.vue')
},
{
path: '/dashboard-enhanced', // 新增
name: 'DashboardEnhanced',
component: () => import('@/views/DashboardV2Enhanced.vue')
}
```
然后导航栏添加链接:
```vue
<router-link to="/dashboard-enhanced">Dashboard 增强版</router-link>
```
---
## 📊 API 使用示例
### 示例 1:获取策略列表并筛选
```javascript
// 获取所有低估值策略
const strategies = await fetchStrategiesList({
style: 'value',
risk_level: 'low'
})
console.log(strategies)
// {
// strategies: [
// {
// id: 'value_focus',
// name: '深度低估',
// metrics: { ... },
// top_stocks: [ ... ],
// recommendation_score: 78
// }
// ]
// }
```
### 示例 2:获取风险总览
```javascript
// 获取当前风险状况
const risk = await fetchRiskOverview()
console.log(risk)
// {
// overall_risk_score: 45,
// risk_level: 'medium',
// dimensions: {
// policy: 35,
// liquidity: 52,
// technical: 48,
// sentiment: 41
// }
// }
```
### 示例 3:策略风险联动
```javascript
// 获取风险对策略的影响
const impact = await fetchStrategyRiskImpact()
console.log(impact)
// {
// current_environment: '中等风险震荡市',
// recommended_strategies: [
// {
// strategy_id: 'defensive_stable',
// reason: '当前宏观风险偏高,稳健策略更适合',
// weight_adjustment: '+20%'
// }
// ],
// affected_strategies: [
// {
// strategy_id: 'momentum_trend',
// impact: 'negative',
// reason: '市场波动加剧,动量策略回撤风险上升',
// weight_adjustment: '-25%'
// }
// ]
// }
```
---
## 🎨 自定义调整
### 调整策略配置
编辑 `backend/app/routes/strategies.py`:
```python
STRATEGY_CONFIGS = {
"my_custom_strategy": {
"id": "my_custom_strategy",
"name": "我的自定义策略",
"tagline": "一句话描述",
"style": "comprehensive",
"period": "mid",
"risk_level": "medium",
"description": "详细描述",
"filters": {
# 筛选条件
}
}
}
```
### 调整风险事件
编辑 `backend/app/routes/risk_radar.py` 中的 `_generate_risk_events()` 函数。
### 调整UI配色
编辑 `frontend/src/assets/styles/variables.css`(或你的全局样式文件):
```css
:root {
--success: #10b981; /* 低风险 */
--warn: #f59e0b; /* 中风险 */
--risk: #ef4444; /* 高风险 */
--pri: #7c3aed; /* 主色调 */
}
```
---
## 📈 性能优化建议
### 1. API缓存
策略和风险数据变化较慢,可以添加缓存:
```python
# backend/app/routes/strategies.py
from app.modules.cache_manager import cache, CACHE_KEYS
@router.get("/list")
async def get_strategies_list(...):
cache_key = f"strategies:list:{style}:{period}:{risk_level}"
cached = cache.get(cache_key)
if cached:
return cached
# ... 计算数据
cache.set(cache_key, result, ttl=300) # 5分钟缓存
return result
```
### 2. 组件懒加载
抽屉组件可以懒加载:
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
const StrategyDetailDrawer = defineAsyncComponent(() =>
import('@/components/StrategyDetailDrawer.vue')
)
</script>
```
### 3. 虚拟滚动
如果策略/风险事件很多,可以使用虚拟滚动:
```bash
npm install vue-virtual-scroller
```
---
## 🔐 生产环境部署
### Docker 部署
```bash
# 构建镜像
docker-compose build
# 启动所有服务
docker-compose up -d
# 查看日志
docker-compose logs -f backend
```
### 环境变量配置
```bash
# .env
# API Keys
OPENROUTER_API_KEY=your_api_key
TUSHARE_TOKEN=your_token
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/stockai
# Redis
REDIS_URL=redis://localhost:6379
# Cache TTL
CACHE_TTL_STRATEGY=300 # 策略缓存5分钟
CACHE_TTL_RISK=180 # 风险缓存3分钟
```
---
## 📞 技术支持
如有问题,请查看:
1. `DASHBOARD_OPTIMIZATION_GUIDE.md` - 完整实施指南
2. `CLAUDE.md` - 项目架构文档
3. API文档: http://localhost:8000/docs
---
## ✅ 部署检查清单
最后检查:
- [ ] 后端服务运行正常(http://localhost:8000/health)
- [ ] 所有新 API 测试通过(`./test_dashboard_apis.sh`)
- [ ] 前端编译无错误(`npm run dev`)
- [ ] 浏览器访问 Dashboard 无报错
- [ ] 策略卡片显示完整
- [ ] 策略详情抽屉可打开
- [ ] 风险仪表盘正常显示
- [ ] 风险事件列表正常显示
- [ ] 风险时间线正常显示
- [ ] 策略风险联动生效
**全部勾选后,恭喜你完成了 Dashboard 优化部署!** 🎉
---
**最后更新:** 2025-11-16
**版本:** v1.0.0