多账户组合管理,支持 FIFO/均价成本计算、FX 汇率换算、CSV 导入、组合快照回放。
| 文件 | 职责 |
|---|---|
portfolio_service.py |
PortfolioService 核心服务(FIFO/均价成本、FX 换算、快照回放) |
import_service.py |
ImportService 雪球/富途/通用 CSV 交易导入 |
risk_service.py |
PortfolioRiskService 组合风险计算 |
__init__.py |
导出 |
账户管理
create_account(name: str, currency: str = "USD", description: str = "") -> dictget_accounts() -> List[dict]get_account(account_id: int) -> dictdelete_account(account_id: int) -> bool
交易记录
add_transaction(account_id: int, code: str, action: str, shares: float, price: float, fee: float = 0, date: str = None) -> dict- action:
"buy"/"sell"/"dividend"
- action:
get_transactions(account_id: int, code: str = None) -> List[dict]delete_transaction(transaction_id: int) -> bool
持仓计算
get_positions(account_id: int) -> List[dict]— 当前持仓- 返回每只股票:
{code, name, shares, avg_cost, current_price, market_value, pnl, pnl_pct} - 成本计算: FIFO 或均价(根据配置)
- 返回每只股票:
get_position_detail(account_id: int, code: str) -> dict— 单只持仓详情
组合概览
get_overview(account_id: int) -> dict— 组合概览- 返回:
{total_value, total_cost, total_pnl, total_pnl_pct, cash, positions_count, currency}
- 返回:
get_performance(account_id: int, days: int = 30) -> List[dict]— 历史表现(快照回放)
FX 汇率
_convert_currency(amount: float, from_ccy: str, to_ccy: str) -> float— 汇率换算- 支持 USD/CNY/HKD 互转
CSV 交易记录导入。
import_file(account_id: int, file_path: str, format: str = "auto") -> dict— 导入 CSV- 支持格式: 通用格式 / 雪球导出 / 富途导出 / 自定义映射
- 返回:
{imported: int, skipped: int, errors: List[str]}
detect_format(file_path: str) -> str— 自动检测 CSV 格式_parse_row(row: dict, format: str) -> dict— 解析单行
组合风险计算。
calculate_risk(account_id: int) -> dict— 计算组合风险指标- 返回:
{concentration, sector_exposure, beta, var_95, max_drawdown}
- 返回:
- 依赖:
config、storage(PortfolioRepo)、tickbridge(实时行情) - 被依赖:
api(portfolio 端点)、agent(PortfolioAgent)
无专属环境变量,通过 API 参数控制。
- FIFO 成本计算:卖出时按最早买入的成本价计算盈亏
- 均价成本:所有买入的加权平均价
- FX 汇率通过 akshare 获取,缓存 1 小时
- CSV 导入支持自动检测编码(UTF-8 / GBK)
- 组合快照每日自动保存(通过 API 触发)