88 lines
2.7 KiB
Python
Executable File
88 lines
2.7 KiB
Python
Executable File
"""Virtual portfolios: each strategy trades its own isolated slice of capital."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime
|
|
from typing import Literal
|
|
|
|
DUST = 1e-10
|
|
|
|
|
|
@dataclass
|
|
class Position:
|
|
volume: float
|
|
avg_price: float # includes buy fees
|
|
|
|
|
|
@dataclass
|
|
class Fill:
|
|
pair: str
|
|
side: Literal["buy", "sell"]
|
|
volume: float
|
|
price: float
|
|
fee: float
|
|
time: datetime
|
|
txid: str | None = None
|
|
|
|
|
|
@dataclass
|
|
class Portfolio:
|
|
cash: float
|
|
positions: dict[str, Position] = field(default_factory=dict)
|
|
|
|
def volume(self, pair: str) -> float:
|
|
pos = self.positions.get(pair)
|
|
return pos.volume if pos else 0.0
|
|
|
|
def market_value(self, pair: str, prices: dict[str, float]) -> float:
|
|
return self.volume(pair) * prices.get(pair, 0.0)
|
|
|
|
def equity(self, prices: dict[str, float]) -> float:
|
|
return self.cash + sum(self.market_value(p, prices) for p in self.positions)
|
|
|
|
def weights(self, prices: dict[str, float]) -> dict[str, float]:
|
|
total = self.equity(prices)
|
|
if total <= 0:
|
|
return {}
|
|
return {p: self.market_value(p, prices) / total for p in self.positions}
|
|
|
|
def apply(self, fill: Fill) -> float | None:
|
|
"""Apply a fill and return realized P&L for sells."""
|
|
pos = self.positions.get(fill.pair)
|
|
if fill.side == "buy":
|
|
cost = fill.volume * fill.price + fill.fee
|
|
self.cash -= cost
|
|
if pos is None:
|
|
self.positions[fill.pair] = Position(fill.volume, cost / fill.volume)
|
|
else:
|
|
new_volume = pos.volume + fill.volume
|
|
pos.avg_price = (pos.volume * pos.avg_price + cost) / new_volume
|
|
pos.volume = new_volume
|
|
return None
|
|
|
|
if pos is None or fill.volume > pos.volume + DUST:
|
|
raise ValueError(f"Cannot sell {fill.volume} {fill.pair}: position too small")
|
|
self.cash += fill.volume * fill.price - fill.fee
|
|
pnl = fill.volume * (fill.price - pos.avg_price) - fill.fee
|
|
pos.volume -= fill.volume
|
|
if pos.volume <= DUST:
|
|
del self.positions[fill.pair]
|
|
return pnl
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
"cash": self.cash,
|
|
"positions": {
|
|
p: {"volume": pos.volume, "avg_price": pos.avg_price}
|
|
for p, pos in self.positions.items()
|
|
},
|
|
}
|
|
|
|
@classmethod
|
|
def from_dict(cls, data: dict) -> Portfolio:
|
|
return cls(
|
|
cash=data["cash"],
|
|
positions={p: Position(**v) for p, v in data.get("positions", {}).items()},
|
|
)
|