"""Ledger aggregato del portafoglio: capitale, allocazioni, equity, PnL, peak/DD, persistenza.""" from __future__ import annotations import json from datetime import datetime, timezone from pathlib import Path class PortfolioLedger: def __init__(self, code: str, total_capital: float = 1000.0, data_dir: Path = Path("data/portfolios")): self.code = code self.initial_capital = total_capital self.total_capital = total_capital self.work_dir = Path(data_dir) / code self.work_dir.mkdir(parents=True, exist_ok=True) self.status_path = self.work_dir / "status.json" self.equity_path = self.work_dir / "equity.jsonl" self.events_path = self.work_dir / "events.jsonl" self.equity = total_capital self.peak = total_capital self.max_dd = 0.0 self.weights: dict[str, float] = {} self.alloc: dict[str, float] = {} self.last_rebalance = "" self._load() def _load(self): if not self.status_path.exists(): return s = json.loads(self.status_path.read_text()) self.total_capital = s.get("total_capital", self.total_capital) self.equity = s.get("equity", self.equity) self.peak = s.get("peak", self.peak) self.max_dd = s.get("max_dd", self.max_dd) self.weights = s.get("weights", {}) self.alloc = s.get("alloc", {}) self.last_rebalance = s.get("last_rebalance", "") def allocate(self, weights: dict[str, float]) -> dict[str, float]: self.weights = dict(weights) self.alloc = {sid: round(self.total_capital * w, 6) for sid, w in weights.items()} self.last_rebalance = datetime.now(timezone.utc).isoformat() self._append(self.events_path, {"event": "rebalance", "weights": self.weights, "total_capital": self.total_capital}) return self.alloc def update_equity(self, sleeve_equity: dict[str, float], pnl_day: float = 0.0): self.equity = float(sum(sleeve_equity.values())) if self.equity > self.peak: self.peak = self.equity dd = (self.peak - self.equity) / self.peak * 100 if self.peak > 0 else 0.0 self.max_dd = max(self.max_dd, dd) self._append(self.equity_path, { "ts": datetime.now(timezone.utc).isoformat(), "equity": round(self.equity, 2), "dd": round(dd, 3), "pnl_day": round(pnl_day, 2), "pnl_total": round(self.equity - self.initial_capital, 2), }) def save(self): self.status_path.write_text(json.dumps({ "code": self.code, "total_capital": round(self.total_capital, 2), "equity": round(self.equity, 2), "peak": round(self.peak, 2), "max_dd": round(self.max_dd, 3), "weights": self.weights, "alloc": self.alloc, "last_rebalance": self.last_rebalance, "ts": datetime.now(timezone.utc).isoformat(), }, indent=2)) @staticmethod def _append(path: Path, row: dict): with open(path, "a") as f: f.write(json.dumps(row) + "\n")