feat(portfolio): PortfolioLedger (alloc, equity/DD, persistenza+resume)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,26 @@
|
||||
from pathlib import Path
|
||||
from src.portfolio.ledger import PortfolioLedger
|
||||
|
||||
|
||||
def test_alloc_split_by_weights(tmp_path):
|
||||
L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
|
||||
alloc = L.allocate({"a": 0.6, "b": 0.4})
|
||||
assert alloc == {"a": 600.0, "b": 400.0}
|
||||
|
||||
|
||||
def test_update_tracks_equity_and_dd(tmp_path):
|
||||
L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
|
||||
L.update_equity({"a": 700.0, "b": 500.0})
|
||||
assert L.equity == 1200.0 and L.peak == 1200.0 and L.max_dd == 0.0
|
||||
L.update_equity({"a": 500.0, "b": 400.0})
|
||||
assert L.equity == 900.0
|
||||
assert abs(L.max_dd - 25.0) < 1e-9
|
||||
|
||||
|
||||
def test_persist_and_resume(tmp_path):
|
||||
L = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
|
||||
L.update_equity({"a": 1100.0})
|
||||
L.save()
|
||||
L2 = PortfolioLedger("PORTX", total_capital=1000.0, data_dir=tmp_path)
|
||||
assert L2.equity == 1100.0 and L2.peak == 1100.0
|
||||
assert (tmp_path / "PORTX" / "equity.jsonl").exists()
|
||||
Reference in New Issue
Block a user