跳轉到

開發指南 (For Claude Code)

給 Claude Code 的說明

這份文檔是專門為 Claude Code 準備的開發指南。請按照以下順序閱讀所有規格文檔,然後開始實作。


📚 必讀文檔順序

  1. ARCHITECTURE.md - 理解整體架構和設計理念
  2. CORE_SPEC.md - 核心框架的詳細規格
  3. INVESTMENT_AGENT_SPEC.md - 投資 Agent 的實現規格
  4. DATA_PIPELINE_SPEC.md - 資料管道實現規格
  5. DATABASE_SCHEMA.md - 資料庫設計
  6. API_SPEC.md - API 端點規格
  7. DEPLOYMENT.md - 部署配置
  8. 本文檔 - 開發流程與注意事項

🎯 開發目標

Phase 1 MVP (3-4 週): - ✅ Core Framework (LLM, Agent Framework, RAG) - ✅ Investment Agent (單股分析) - ✅ Data Pipeline (台股全部 + 美股七巨頭) - ✅ 28 種技術指標(62 欄位) - ✅ FastAPI Backend - ✅ Streamlit UI - ✅ Docker 部署


🛠️ 開發環境設定

1. 建立專案結構

# 建立目錄
mkdir -p cortex/{core,investment-agent,docs}
cd cortex

# 建立子目錄
mkdir -p core/{llm,agent_framework,knowledge,utils,models,tests}
mkdir -p investment-agent/{backend,streamlit_ui,tests}
mkdir -p investment-agent/backend/{api,agents,data_pipeline,database,knowledge,config}

2. 初始化 Python 環境

# 建立虛擬環境
python3.11 -m venv venv
source venv/bin/activate

# 安裝開發工具
pip install black isort flake8 pytest pytest-asyncio mypy

3. requirements.txt

core/requirements.txt:

google-generativeai>=0.3.0
langchain>=0.1.0
langgraph>=0.0.20
chromadb>=0.4.0
pydantic>=2.0.0
pyyaml>=6.0
python-dotenv>=1.0.0
aiohttp>=3.9.0
jinja2>=3.1.0

investment-agent/backend/requirements.txt:

-e ../../core

fastapi>=0.109.0
uvicorn[standard]>=0.27.0
sqlalchemy[asyncio]>=2.0.0
asyncpg>=0.29.0
alembic>=1.13.0
yfinance>=0.2.35
pandas>=2.1.0
pandas-ta>=0.3.14
apscheduler>=3.10.0
python-multipart>=0.0.6

streamlit_ui/requirements.txt:

streamlit>=1.30.0
plotly>=5.18.0
requests>=2.31.0
pandas>=2.1.0


📝 開發流程

Phase 1: Core Framework (Week 1)

Step 1.1: LLM 層

# 優先順序 1:建立 BaseLLM
# 檔案:core/llm/base.py
# 參考:CORE_SPEC.md Section 1.1

# 優先順序 2:實現 GeminiLLM
# 檔案:core/llm/gemini.py
# 參考:CORE_SPEC.md Section 1.2
# 注意:
# - 實現 exponential backoff
# - 處理 rate limit
# - 支援 function calling

# 優先順序 3:PromptManager
# 檔案:core/llm/prompt_manager.py
# 參考:CORE_SPEC.md Section 1.3

測試:

pytest core/tests/llm/test_gemini.py -v

Step 1.2: Agent Framework

# 優先順序 1:BaseAgent
# 檔案:core/agent_framework/base_agent.py
# 參考:CORE_SPEC.md Section 2.1

# 優先順序 2:MetaAgent (核心!)
# 檔案:core/agent_framework/meta_agent.py
# 參考:CORE_SPEC.md Section 2.2
# 重點:
# - generate_strategy() 方法
# - 使用 Gemini function calling 確保 JSON 輸出

# 優先順序 3:VRREngine
# 檔案:core/agent_framework/vrr_engine.py
# 參考:CORE_SPEC.md Section 2.3

Step 1.3: Knowledge 層

# 優先順序 1:ChromaVectorStore
# 檔案:core/knowledge/vector_store.py
# 參考:CORE_SPEC.md Section 3.1

# 優先順序 2:RAGService
# 檔案:core/knowledge/rag_service.py
# 參考:CORE_SPEC.md Section 3.2

Step 1.4: Models 與 Utils

# 資料模型
# 檔案:core/models/*.py
# 參考:CORE_SPEC.md Section 5

# 工具函數
# 檔案:core/utils/*.py
# 參考:CORE_SPEC.md Section 4

里程碑檢查:

# 所有 core 測試通過
pytest core/tests/ -v --cov=core --cov-report=html

# 測試 Meta-Agent 能生成策略
python -c "
from core.llm import GeminiLLM
from core.agent_framework import MetaAgent

llm = GeminiLLM(api_key='...')
meta = MetaAgent(llm=llm)
strategy = await meta.generate_strategy('分析台積電', 'investment')
print(strategy)
"


Phase 2: Database & Data Pipeline (Week 2)

Step 2.1: 資料庫設定

# 1. 建立 models
# 檔案:investment-agent/backend/database/models.py
# 參考:DATABASE_SCHEMA.md Section 2

# 2. 建立 CRUD
# 檔案:investment-agent/backend/database/crud.py
# 參考:DATABASE_SCHEMA.md Section "CRUD 操作"

# 3. Alembic 遷移
alembic init alembic
alembic revision --autogenerate -m "Initial schema"

Step 2.2: Data Pipeline

# 優先順序 1:OHLC 抓取(FinMind 為主、yfinance 備援)
# 檔案:investment-agent/backend/scripts/taiwan_stocks.py

# 優先順序 2:Indicator Calculator
# 檔案:investment-agent/backend/data_pipeline/indicators.py
# 參考:DATA_PIPELINE_SPEC.md Section 2
# 注意:15+ 指標,使用 pandas_ta

# 優先順序 3:Scheduler(排程入口)
# 檔案:investment-agent/backend/scripts/scheduler.py
# 參考:DATA_PIPELINE_SPEC.md Section 1

里程碑檢查:

# 測試指標計算(手動驗證腳本)
python scripts/test_indicators.py 2330.TW

# 立即執行一次每日更新(再進入排程)
python scripts/scheduler.py --run-now


Phase 3: Investment Agent (Week 2-3)

Step 3.1: 領域知識

# 檔案:investment-agent/backend/knowledge/stock_knowledge.py
# 參考:INVESTMENT_AGENT_SPEC.md Section 4

# 準備知識文件
# 目錄:docs/knowledge/indicators/*.md
# 內容:RSI, MACD, MA 等指標解讀

Step 3.2: Agent 實現

# 優先順序 1:TechnicalCalculator
# 檔案:investment-agent/backend/agents/calculator.py
# 參考:INVESTMENT_AGENT_SPEC.md Section 1.2

# 優先順序 2:VerifierAgent
# 檔案:investment-agent/backend/agents/verifier.py
# 參考:INVESTMENT_AGENT_SPEC.md Section 1.3

# 優先順序 3:StockAnalyzer
# 檔案:investment-agent/backend/agents/analyzer.py
# 參考:INVESTMENT_AGENT_SPEC.md Section 1.1
# 這是最複雜的部分!

Step 3.3: LangGraph 工作流程

# 檔案:investment-agent/backend/agents/coordinator.py
# 參考:INVESTMENT_AGENT_SPEC.md Section 2
# 注意:
# - 定義 AnalysisState
# - 建立 StateGraph
# - 實現所有節點函數
# - 條件邊 (should_refine)

里程碑檢查:

# 測試完整分析流程
python -c "
from agents.coordinator import StockAnalysisWorkflow

workflow = StockAnalysisWorkflow(...)
result = await workflow.run(ticker='2330.TW')
print(result.summary)
"


Phase 4: API & UI (Week 3-4)

Step 4.1: FastAPI

# 優先順序 1:基礎設定
# 檔案:investment-agent/backend/api/main.py
# 參考:API_SPEC.md "FastAPI 實現"

# 優先順序 2:路由
# 檔案:investment-agent/backend/api/routes/*.py
# - stocks.py (股票查詢)
# - analyze.py (分析端點)
# 參考:API_SPEC.md 各 Section

# 優先順序 3:測試
pytest investment-agent/tests/api/ -v

Step 4.2: Streamlit UI

# 優先順序 1:基礎框架
# 檔案:investment-agent/streamlit_ui/app.py
# 功能:
# - 股票搜尋
# - 分析請求
# - 結果顯示

# 優先順序 2:圖表組件
# 檔案:investment-agent/streamlit_ui/components/chart.py
# 使用 Plotly 繪製:
# - K 線圖
# - 技術指標圖

# 優先順序 3:對話介面
# 檔案:investment-agent/streamlit_ui/pages/chat.py

Phase 5: 整合與測試 (Week 4)

Step 5.1: Docker 化

# 1. 建立 Dockerfiles
# 參考:DEPLOYMENT.md

# 2. docker-compose.yml
# 參考:DEPLOYMENT.md

# 3. 測試啟動
docker-compose up -d
docker-compose logs -f

Step 5.2: 端對端測試

# 1. 資料更新
curl -X POST http://localhost:8000/api/admin/update-data

# 2. 股票分析
curl -X POST http://localhost:8000/api/analyze \
  -H "Content-Type: application/json" \
  -d '{"ticker": "2330.TW", "analysis_type": "comprehensive"}'

# 3. UI 測試
# 瀏覽 http://localhost:8501

Step 5.3: 效能測試

# 測試指標:
# - Agent 回應時間 < 5 秒
# - VRR 通過率 > 80%
# - 資料更新成功率 > 95%

# 壓力測試
ab -n 100 -c 10 http://localhost:8000/api/stocks/2330.TW

⚠️ 重要注意事項

1. Meta-Agent 實現

# 這是整個系統的核心!
# 務必確保:
# 1. 使用 Gemini function calling 確保 JSON 輸出
# 2. 策略包含所有必要欄位
# 3. 處理 LLM 輸出錯誤

# 範例
response = await self.llm.generate_structured(
    prompt=prompt,
    schema={
        "type": "object",
        "properties": {
            "verify_criteria": {"type": "array", "items": {"type": "string"}},
            "reflect_focus": {"type": "array", "items": {"type": "string"}},
            "refine_priority": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["verify_criteria", "reflect_focus", "refine_priority"]
    }
)

2. 錯誤處理

# 所有 async 函數都要有 try-except
try:
    result = await some_async_function()
except Exception as e:
    logger.error(f"Error: {e}", exc_info=True)
    # 適當處理錯誤

3. 日誌記錄

# 關鍵操作都要記錄
logger.info("Starting analysis for {ticker}")
logger.debug("Generated strategy: {strategy}")
logger.error("Analysis failed: {error}")

4. 測試覆蓋率

# 目標:
# - Core: 80%+
# - Agent: 70%+
# - API: 60%+

pytest --cov=. --cov-report=html

5. 配置管理

# 所有可調參數都放 YAML
# 不要寫死在程式碼中
config = Config("config/")
value = config.get("llm.gemini.temperature")

🐛 常見問題解決

Q1: Gemini API rate limit

# 實現 exponential backoff
for attempt in range(max_retries):
    try:
        return await self.api_call()
    except RateLimitError:
        wait_time = 2 ** attempt
        await asyncio.sleep(wait_time)

Q2: yfinance 資料不完整

# 檢查並補齊
if df.empty:
    logger.warning(f"{ticker} 無資料")
    return None

# 處理 NaN
df = df.dropna()

Q3: LangGraph 狀態傳遞

# 確保狀態正確更新
state["field"] = value
return state  # 一定要 return!

Q4: PostgreSQL 連接問題

# 檢查
docker-compose exec postgres pg_isready

# 重啟
docker-compose restart postgres

✅ 開發檢查清單

Core Framework

  • [ ] GeminiLLM 實現並測試通過
  • [ ] MetaAgent 能生成有效策略
  • [ ] VRREngine 執行完整流程
  • [ ] ChromaVectorStore 正常運作
  • [ ] 所有 core 測試通過(80%+ 覆蓋率)

Data Pipeline

  • [ ] 能成功爬取台股和美股資料
  • [ ] 計算 28 種技術指標(62 欄位)
  • [ ] APScheduler 定時任務正常
  • [ ] 資料驗證通過
  • [ ] 錯誤處理和重試機制

Investment Agent

  • [ ] StockAnalyzer 完整實現
  • [ ] LangGraph 工作流程運作
  • [ ] VRR 驗證通過率 > 80%
  • [ ] 分析結果結構化且完整
  • [ ] 領域知識整合成功

API

  • [ ] 所有端點實現並測試
  • [ ] 錯誤處理完善
  • [ ] API 文檔正確

UI

  • [ ] Streamlit 介面完整
  • [ ] 圖表正常顯示
  • [ ] 使用者體驗流暢

部署

  • [ ] Docker Compose 正常啟動
  • [ ] 所有服務健康
  • [ ] 資料庫遷移成功
  • [ ] 環境變數正確設定

📊 效能基準

Agent 效能

  • Meta-Agent 策略生成: < 2 秒
  • 股票分析(單次): < 5 秒
  • VRR 迭代(3次上限): < 15 秒

資料管道

  • 單支股票爬取: < 5 秒
  • 技術指標計算: < 1 秒/股票
  • 全市場更新: < 30 分鐘(1700 支台股)

API

  • 股票查詢: < 100ms
  • 分析端點: < 5 秒

🎓 學習資源

LangGraph

  • 官方文檔: https://langchain-ai.github.io/langgraph/
  • 範例: https://github.com/langchain-ai/langgraph/tree/main/examples

Gemini API

  • 官方文檔: https://ai.google.dev/docs
  • Function Calling: https://ai.google.dev/docs/function_calling

FastAPI

  • 官方文檔: https://fastapi.tiangolo.com/

🚀 開始開發!

# 1. 確認環境
python --version  # 3.11+
docker --version  # 20.10+

# 2. 安裝依賴
pip install -r core/requirements.txt
pip install -r investment-agent/backend/requirements.txt

# 3. 設定環境變數
cp .env.example .env
# 編輯 .env 填入 GOOGLE_API_KEY

# 4. 開始開發 Core
cd core
pytest tests/ -v

# 祝你開發順利!

文檔版本: 1.0
最後更新: 2025-02-01
作者: Leon (AI/ML Engineer)