add docker

This commit is contained in:
aaron 2025-09-18 20:54:30 +08:00
parent adcc8844b1
commit ad6963fc3f
5 changed files with 804 additions and 0 deletions

83
.dockerignore Normal file
View File

@ -0,0 +1,83 @@
# Git
.git
.gitignore
# Python
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env
pip-log.txt
pip-delete-this-directory.txt
.tox
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.log
.DS_Store
.mypy_cache
.pytest_cache
.hypothesis
# Virtual environments
venv/
env/
ENV/
.venv/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Documentation
*.md
docs/
# Test files
tests/
test_*.py
*_test.py
# Development tools
.pre-commit-config.yaml
.flake8
.black
# Logs
logs/
*.log
# Temporary files
tmp/
temp/
.tmp
# Docker
Dockerfile
docker-compose*.yml
.dockerignore
# Jupyter notebooks
*.ipynb
.ipynb_checkpoints/
# Local data (will be mounted as volume)
data/local_*
data/temp_*
# Build artifacts
build/
dist/
*.egg-info/

367
DOCKER_DEPLOY.md Normal file
View File

@ -0,0 +1,367 @@
# A股量化交易系统 Docker 部署指南
## 📋 概述
本指南将帮助您使用 Docker 快速部署 A股量化交易系统。系统包含 Web 界面、数据采集服务和可选的 Nginx 反向代理。
## 🔧 环境要求
- Docker >= 20.10
- Docker Compose >= 2.0
- 系统内存 >= 2GB
- 磁盘空间 >= 5GB
## 🚀 快速开始
### 1. 克隆项目
```bash
git clone <your-repo-url>
cd TradingAI
```
### 2. 一键启动
```bash
# 使用启动脚本(推荐)
./docker-start.sh start
# 或者直接使用 docker-compose
docker-compose up -d
```
### 3. 访问系统
- Web 界面http://localhost:8080
- Nginx 代理http://localhost如果启用
## 📁 项目结构
```
TradingAI/
├── Dockerfile # 主应用镜像
├── docker-compose.yml # 服务编排配置
├── docker-start.sh # 启动管理脚本
├── .dockerignore # Docker 忽略文件
├── config/ # 配置文件目录
├── data/ # 数据持久化目录
├── logs/ # 日志文件目录
└── nginx/ # Nginx 配置目录
```
## 🐳 服务说明
### trading-web
- **功能**Web 界面服务
- **端口**8080
- **健康检查**/api/stats
- **数据卷**
- `./data:/app/data` - 数据库文件
- `./config:/app/config` - 配置文件
- `./logs:/app/logs` - 日志文件
### trading-collector
- **功能**:数据采集和策略执行
- **调度**:每天 9:00 和 15:00 执行
- **依赖**trading-web
### nginx可选
- **功能**:反向代理和负载均衡
- **端口**80, 443
- **配置**nginx/nginx.conf
## ⚙️ 配置文件
### config/config.yaml
```yaml
# 数据库配置
database:
path: "data/trading.db"
# 数据源配置
data_source:
provider: "adata"
# 策略配置
strategy:
kline_pattern:
min_entity_ratio: 0.55
final_yang_min_ratio: 0.40
max_turnover_ratio: 40.0
timeframes: ["daily", "weekly"]
# 通知配置
notification:
dingtalk:
enabled: false
webhook_url: ""
# 日志配置
logging:
level: "INFO"
file: "logs/trading.log"
```
## 🛠️ 管理命令
### 使用启动脚本
```bash
# 启动所有服务
./docker-start.sh start
# 停止所有服务
./docker-start.sh stop
# 重启服务
./docker-start.sh restart
# 查看实时日志
./docker-start.sh logs
# 清理所有数据(危险操作)
./docker-start.sh cleanup
```
### 使用 Docker Compose
```bash
# 启动服务
docker-compose up -d
# 停止服务
docker-compose down
# 查看服务状态
docker-compose ps
# 查看日志
docker-compose logs -f [service_name]
# 重启特定服务
docker-compose restart trading-web
# 重新构建镜像
docker-compose build --no-cache
# 扩展服务实例
docker-compose up -d --scale trading-web=2
```
## 📊 监控和调试
### 健康检查
系统提供了健康检查端点:
```bash
# 检查 Web 服务状态
curl http://localhost:8080/api/stats
# 检查 Docker 容器健康状态
docker-compose ps
```
### 日志查看
```bash
# 查看所有服务日志
docker-compose logs -f
# 查看特定服务日志
docker-compose logs -f trading-web
# 查看容器内日志文件
docker exec -it trading-ai-web tail -f /app/logs/trading.log
```
### 进入容器调试
```bash
# 进入 Web 服务容器
docker exec -it trading-ai-web bash
# 进入采集服务容器
docker exec -it trading-ai-collector bash
# 查看容器资源使用情况
docker stats
```
## 🔧 自定义配置
### 修改端口
编辑 `docker-compose.yml`
```yaml
services:
trading-web:
ports:
- "9090:8080" # 将外部端口改为 9090
```
### 添加环境变量
```yaml
services:
trading-web:
environment:
- FLASK_ENV=production
- DATABASE_URL=sqlite:///data/trading.db
- LOG_LEVEL=DEBUG
```
### 配置数据持久化
```yaml
services:
trading-web:
volumes:
- trading-data:/app/data
- ./config:/app/config:ro # 只读挂载
volumes:
trading-data:
driver: local
```
## 🛡️ 安全配置
### SSL/HTTPS 配置
1. 将 SSL 证书放置在 `nginx/ssl/` 目录
2. 修改 `nginx/nginx.conf` 添加 HTTPS 配置:
```nginx
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# SSL 配置...
}
```
### 防火墙配置
```bash
# 只允许必要端口
sudo ufw allow 80
sudo ufw allow 443
sudo ufw allow 8080
```
## 🚨 故障排除
### 常见问题
1. **端口被占用**
```bash
# 查找占用端口的进程
sudo lsof -i :8080
# 修改 docker-compose.yml 中的端口映射
```
2. **权限问题**
```bash
# 修复数据目录权限
sudo chown -R $USER:$USER data/ logs/
```
3. **内存不足**
```bash
# 清理不使用的镜像
docker system prune -a
# 限制容器内存使用
docker-compose up -d --memory="1g"
```
4. **数据库锁定**
```bash
# 重启服务解决数据库锁定
docker-compose restart trading-web
```
### 日志级别调整
修改 `config/config.yaml`
```yaml
logging:
level: "DEBUG" # DEBUG, INFO, WARNING, ERROR
file: "logs/trading.log"
```
## 📈 性能优化
### 资源限制
```yaml
services:
trading-web:
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
```
### 缓存优化
```bash
# 使用多阶段构建减小镜像大小
# 启用 Docker BuildKit
export DOCKER_BUILDKIT=1
docker-compose build
```
## 🔄 更新和备份
### 更新系统
```bash
# 拉取最新代码
git pull
# 重新构建和启动
docker-compose up -d --build
```
### 备份数据
```bash
# 备份数据库和配置
tar -czf backup-$(date +%Y%m%d).tar.gz data/ config/
# 使用 Docker 卷备份
docker run --rm -v trading_data:/data -v $(pwd):/backup ubuntu tar czf /backup/data-backup.tar.gz /data
```
### 恢复数据
```bash
# 恢复备份
tar -xzf backup-20231201.tar.gz
# 重启服务
docker-compose restart
```
## 📞 支持
如果遇到问题,请:
1. 查看本文档的故障排除部分
2. 检查容器日志:`docker-compose logs -f`
3. 提交 GitHub Issue 并附上相关日志
## 📄 许可证
本项目采用 MIT 许可证,详见 LICENSE 文件。

42
Dockerfile Normal file
View File

@ -0,0 +1,42 @@
# 使用Python 3.11官方镜像
FROM python:3.11-slim
# 设置工作目录
WORKDIR /app
# 设置环境变量
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV FLASK_APP=web/app.py
ENV FLASK_ENV=production
# 安装系统依赖
RUN apt-get update && apt-get install -y \
gcc \
g++ \
&& rm -rf /var/lib/apt/lists/*
# 复制requirements文件
COPY requirements.txt .
# 安装Python依赖
RUN pip install --no-cache-dir -r requirements.txt
# 复制项目文件
COPY . .
# 创建数据目录
RUN mkdir -p /app/data
# 设置权限
RUN chmod +x start_web.py
# 暴露端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/api/stats || exit 1
# 启动命令
CMD ["python", "start_web.py"]

95
docker-compose.yml Normal file
View File

@ -0,0 +1,95 @@
version: '3.8'
services:
# 交易系统Web应用
trading-web:
build: .
container_name: trading-ai-web
ports:
- "8080:8080"
volumes:
# 数据持久化
- ./data:/app/data
# 配置文件
- ./config:/app/config
# 日志文件
- ./logs:/app/logs
environment:
- FLASK_ENV=production
- PYTHONPATH=/app
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/api/stats"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- trading-network
# 数据采集服务(可选)
trading-collector:
build: .
container_name: trading-ai-collector
volumes:
- ./data:/app/data
- ./config:/app/config
- ./logs:/app/logs
environment:
- PYTHONPATH=/app
# 运行数据采集脚本
command: python -c "
import time
import schedule
from src.strategy.kline_pattern_strategy import KlinePatternStrategy
from src.utils.config_loader import ConfigLoader
from loguru import logger
def run_strategy():
try:
config = ConfigLoader()
strategy = KlinePatternStrategy(config)
logger.info('开始运行策略扫描...')
# 这里可以添加具体的策略运行逻辑
logger.info('策略扫描完成')
except Exception as e:
logger.error(f'策略运行失败: {e}')
# 每天9点和15点运行策略
schedule.every().day.at('09:00').do(run_strategy)
schedule.every().day.at('15:00').do(run_strategy)
logger.info('数据采集服务已启动')
while True:
schedule.run_pending()
time.sleep(60)
"
restart: unless-stopped
depends_on:
- trading-web
networks:
- trading-network
# Nginx反向代理可选
nginx:
image: nginx:alpine
container_name: trading-ai-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
depends_on:
- trading-web
restart: unless-stopped
networks:
- trading-network
networks:
trading-network:
driver: bridge
volumes:
trading-data:
driver: local

217
docker-start.sh Executable file
View File

@ -0,0 +1,217 @@
#!/bin/bash
# A股量化交易系统 Docker 启动脚本
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 输出带颜色的信息
info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# 检查Docker是否安装
check_docker() {
if ! command -v docker &> /dev/null; then
error "Docker 未安装,请先安装 Docker"
exit 1
fi
if ! command -v docker-compose &> /dev/null; then
error "Docker Compose 未安装,请先安装 Docker Compose"
exit 1
fi
success "Docker 环境检查通过"
}
# 创建必要的目录
create_directories() {
info "创建必要的目录..."
mkdir -p data logs config nginx/ssl
# 如果配置文件不存在,创建默认配置
if [ ! -f "config/config.yaml" ]; then
warning "配置文件不存在,创建默认配置..."
cat > config/config.yaml << EOF
# A股量化交易系统配置
database:
path: "data/trading.db"
data_source:
provider: "adata"
strategy:
kline_pattern:
min_entity_ratio: 0.55
final_yang_min_ratio: 0.40
max_turnover_ratio: 40.0
timeframes: ["daily", "weekly"]
notification:
dingtalk:
enabled: false
webhook_url: ""
logging:
level: "INFO"
file: "logs/trading.log"
EOF
success "已创建默认配置文件"
fi
}
# 创建Nginx配置
create_nginx_config() {
if [ ! -f "nginx/nginx.conf" ]; then
info "创建 Nginx 配置文件..."
mkdir -p nginx
cat > nginx/nginx.conf << EOF
events {
worker_connections 1024;
}
http {
upstream trading_app {
server trading-web:8080;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://trading_app;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
}
}
EOF
success "已创建 Nginx 配置文件"
fi
}
# 启动服务
start_services() {
info "启动 A股量化交易系统..."
# 构建镜像
info "构建 Docker 镜像..."
docker-compose build
# 启动服务
info "启动服务容器..."
docker-compose up -d
# 等待服务启动
info "等待服务启动..."
sleep 10
# 检查服务状态
if docker-compose ps | grep -q "Up"; then
success "服务启动成功!"
info "Web界面访问地址: http://localhost:8080"
info "如果配置了Nginx: http://localhost"
echo ""
info "查看日志: docker-compose logs -f"
info "停止服务: docker-compose down"
info "重启服务: docker-compose restart"
else
error "服务启动失败,请检查日志"
docker-compose logs
exit 1
fi
}
# 停止服务
stop_services() {
info "停止服务..."
docker-compose down
success "服务已停止"
}
# 查看日志
show_logs() {
docker-compose logs -f
}
# 重启服务
restart_services() {
info "重启服务..."
docker-compose restart
success "服务已重启"
}
# 清理
cleanup() {
warning "这将删除所有容器、镜像和数据卷,是否继续?(y/N)"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
docker-compose down -v --rmi all
success "清理完成"
else
info "取消清理"
fi
}
# 主函数
main() {
case "$1" in
"start")
check_docker
create_directories
create_nginx_config
start_services
;;
"stop")
stop_services
;;
"restart")
restart_services
;;
"logs")
show_logs
;;
"cleanup")
cleanup
;;
*)
echo "A股量化交易系统 Docker 管理脚本"
echo ""
echo "使用方法: $0 {start|stop|restart|logs|cleanup}"
echo ""
echo "命令说明:"
echo " start - 启动服务"
echo " stop - 停止服务"
echo " restart - 重启服务"
echo " logs - 查看日志"
echo " cleanup - 清理所有数据(危险操作)"
echo ""
;;
esac
}
main "$@"