聊天視窗

金融資料科學:從數據到決策的完整流程 - 第 9 章

第 9 章:整合開發與部署

發布於 2026-03-07 13:36

# 第 9 章:整合開發與部署 在前面八章,我們已經從資料蒐集、清理、建模到回測,完成了金融資料科學的核心分析流程。此章的重點是將模型與分析流程搬到實際運營環境中,確保模型能夠持續交付、穩定執行、易於擴充與維護。以下將逐步說明從 **CI/CD**、**容器化**、**雲端服務**、**API 部署** 到 **監控** 的完整實務流程。 --- ## 1. 為什麼需要 CI/CD - **持續交付(Continuous Delivery)**:每次提交都能產生可部署 artefact。 - **持續整合(Continuous Integration)**:每次合併都執行單元測試、靜態分析,保證程式品質。 - **自動化測試**:避免人為錯誤,降低風險。 - **快速回滾**:當部署失敗時可即時回到穩定版。 | CI/CD 典型流程 | 目的 | |---|---| | 編寫程式碼 | 產生功能 | | Push 到 Git | 觸發流水線 | | 依賴安裝 + lint | 代碼風格一致 | | 單元/整合測試 | 功能正確 | | 單元覆蓋率 | 代碼品質 | | Docker Build | 產生容器映像 | | 影像上傳至 registry | 供部署使用 | | 部署至環境 | 實際執行 | | 監控與報警 | 保障運行 | --- ## 2. Git + GitHub Actions 範例 以下示範一個簡易的 **Python** 財務模型專案,使用 GitHub Actions 進行 CI/CD。 ```yaml # .github/workflows/ci-cd.yml name: CI/CD Pipeline on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python 3.10 uses: actions/setup-python@v4 with: python-version: 3.10 - name: Install dependencies run: | pip install -r requirements.txt pip install --upgrade pip pip install flake8 pytest coverage - name: Lint run: flake8 . - name: Test run: pytest --cov=./src tests/ - name: Build Docker image run: | docker build -t finance-model:${{ github.sha }} . - name: Log in to Docker Hub uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Push image run: | docker tag finance-model:${{ github.sha }} yourdockerhub/finance-model:${{ github.sha }} docker push yourdockerhub/finance-model:${{ github.sha }} - name: Deploy to AWS ECS uses: jwalton/gh-ecr-deploy@v1 with: image: yourdockerhub/finance-model:${{ github.sha }} task-definition: ecs-task-def.json cluster: finance-cluster ``` > **備註**:`ecs-task-def.json` 為 ECS 服務使用的 Task Definition,需自行根據實際環境撰寫。 --- ## 3. 容器化:Docker 與 Docker Compose ### 3.1 Dockerfile 範例 ```dockerfile # Dockerfile FROM python:3.10-slim # 設定工作目錄 WORKDIR /app # 安裝系統相依 RUN apt-get update && apt-get install -y \ build-essential \ libssl-dev \ libffi-dev \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # 複製需求檔 COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # 複製專案程式碼 COPY . . # 暴露 API 端口 EXPOSE 8000 # 執行命令(如使用 FastAPI) CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] ``` ### 3.2 Docker Compose ```yaml # docker-compose.yml version: '3.9' services: web: build: . ports: - "8000:8000" environment: - DB_HOST=postgres - DB_PORT=5432 - DB_NAME=finance - DB_USER=finance_user - DB_PASSWORD=secret postgres: image: postgres:15-alpine environment: POSTGRES_DB: finance POSTGRES_USER: finance_user POSTGRES_PASSWORD: secret volumes: - db_data:/var/lib/postgresql/data volumes: db_data: ``` --- ## 4. 雲端部署:AWS 與 GCP | 服務 | 主要用途 | 特色 | |---|---|---| | **AWS ECS (Elastic Container Service)** | 容器編排 | 與 ECR、ALB 無縫整合 | | **AWS Fargate** | 無伺服器容器 | 無需管理 EC2 叢集 | | **GCP Cloud Run** | Serverless 容器 | 自動縮放、簡易設定 | | **AWS Lambda** | 事件驅動 | 可直接執行 Python 3.10 | | **GCP Cloud Functions** | 事件驅動 | 與 GCP 服務整合緊密 | ### 4.1 AWS ECS 範例 1. **建立 ECR Repository**: ```bash aws ecr create-repository --repository-name finance-model ``` 2. **推送映像**: ```bash docker tag finance-model:latest <account-id>.dkr.ecr.<region>.amazonaws.com/finance-model:latest docker push <account-id>.dkr.ecr.<region>.amazonaws.com/finance-model:latest ``` 3. **創建 Task Definition**(`ecs-task-def.json`) ```json { "family": "finance-model-task", "networkMode": "awsvpc", "containerDefinitions": [ { "name": "finance-model", "image": "<account-id>.dkr.ecr.<region>.amazonaws.com/finance-model:latest", "portMappings": [ {"containerPort": 8000, "protocol": "tcp"} ], "memoryReservation": 512, "cpu": 256 } ], "requiresCompatibilities": ["FARGATE"], "cpu": "256", "memory": "512" } ``` 4. **啟動服務**: ```bash aws ecs create-service \ --cluster finance-cluster \ --service-name finance-service \ --task-definition finance-model-task \ --desired-count 2 \ --launch-type FARGATE \ --network-configuration "awsvpcConfiguration={subnets=[subnet-xxxxxx],securityGroups=[sg-xxxxxx],assignPublicIp=ENABLED}" ``` ### 4.2 GCP Cloud Run 範例 ```bash gcloud builds submit --tag gcr.io/<project-id>/finance-model gcloud run deploy finance-service \ --image gcr.io/<project-id>/finance-model \ --platform managed \ --region us-central1 \ --allow-unauthenticated \ --port 8000 ``` --- ## 5. API 部署與網關 - **FastAPI**:輕量、支援 OpenAPI,自動產生 Swagger UI。 - **API Gateway**(AWS API Gateway / GCP Cloud Endpoints):負責流量控制、身份驗證、速率限制。 ```python # app/main.py from fastapi import FastAPI from app.routes import router app = FastAPI(title="金融模型 API") app.include_router(router) # app/routes.py from fastapi import APIRouter, HTTPException from pydantic import BaseModel router = APIRouter() class MarketInput(BaseModel): symbol: str date: str @router.post("/predict") async def predict_market(data: MarketInput): # 讀取模型、計算回報 try: result = model.predict(data.symbol, data.date) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) return {"symbol": data.symbol, "date": data.date, "prediction": result} ``` > **備註**:在實務中,建議將機器學習模型封裝為 **模型服務**(如 TorchServe 或 FastAPI + ONNX),並使用 **模型註冊表**(MLflow)管理模型版本。 --- ## 6. 監控與觀測 | 監控指標 | 工具 | 目的 | |---|---|---| | CPU / Memory | CloudWatch / Stackdriver | 確保資源使用合適 | | 請求成功率 | Prometheus + Grafana | 監測 API 可用性 | | 延遲 (latency) | OpenTelemetry | 優化體驗 | | 錯誤率 | Sentry | 追蹤異常 | | 日誌 | Loki / ELK | 故障排除 | ### 6.1 Prometheus 與 Grafana 範例 ```yaml # prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: "finance-api" metrics_path: "/metrics" static_configs: - targets: ["localhost:8000"] ``` ```bash # 產生 Grafana dashboard curl -X POST -H "Content-Type: application/json" -d @dashboard.json http://localhost:3000/api/dashboards/db ``` --- ## 7. 安全與合規 1. **秘密管理**:使用 **AWS Secrets Manager** 或 **GCP Secret Manager** 來儲存 API 金鑰、資料庫密碼。 2. **網路隔離**:使用 VPC、子網路、Security Group 或 NACL 限制進出流量。 3. **資料加密**:磁碟加密 (EBS encryption, Cloud KMS) 與傳輸加密 (TLS 1.3)。 4. **合規標籤**:為資源加上 **成本中心**、**部門**、**合規等級** 標籤,方便費用與風險追蹤。 --- ## 8. 成本管理與自動縮放 | 服務 | 縮放策略 | |---|---| | **ECS (Fargate)** | CPU / Memory 上限、Application Load Balancer 的 Target Group 內建縮放策略 | | **Cloud Run** | CPU 使用率 > 70% 時自動新增實例,CPU < 30% 時減少實例 | | **Lambda / Cloud Functions** | 事件源自動調整執行緒 | > **技巧**:使用 **Spot Instances** 或 **Preemptible VMs** 減少成本,但需留意不穩定性。 --- ## 9. 案例研究:量化交易策略部署 ### 9.1 預備工作 - **資料庫**:PostgreSQL 存儲歷史行情。 - **模型**:LSTM 產生每日收益預測。 - **服務**:FastAPI + Docker。 - **部署**:AWS ECS + Fargate。 - **監控**:Prometheus + Grafana。 ### 9.2 執行流程 1. **資料更新**:Cron job 下載 Yahoo Finance 資料並寫入資料庫。 2. **模型訓練**:每週一次訓練,使用 **SageMaker** 或 **GCP AI Platform**,模型版本上傳至 **S3**。 3. **API 呼叫**:投資人透過 API 取得預測,並結合交易策略進行自動下單。 4. **風險控管**:API 內置風險限制(每日最大敞口、最大單筆下單金額)。 ### 9.3 成本與效能 - **成本**:每月約 2,000 USD(容器、ECR、ECS、RDS)。 - **效能**:單次預測 < 50 ms,API 可擴展至 10,000 QPS。 - **可靠性**:利用多區域部署,99.99% 可用率。 --- ## 10. 綜合建議與未來方向 | 方向 | 重點 | |---|---| | **自動化測試** | 擴充測試覆蓋度,加入端到端測試。 | **可擴充架構** | 微服務化、使用 **Service Mesh**(Istio)管理流量。 | **AI Ops** | 透過機器學習預測系統健康與資源需求。 | **跨境部署** | 依不同法規使用多雲或國家區域雲。 | **合規追蹤** | 建立合規報表自動化生成,符合 MiFID II / GDPR。 > **結語**:本章展示了從程式碼到雲端服務的完整部署流程。透過 CI/CD、容器化、雲端彈性與監控,我們能夠將金融資料科學模型快速、安全、可靠地投入實際運營。隨著技術的演進,建議持續關注 **IaC**(Terraform、CloudFormation)、**Observability**、**Security Automation** 等領域,確保系統在變更與擴充中保持穩定與合規。