stock-portfolio / parser.py
Amanda Torres
initial commit
d7e86c4
\
"""Stock portfolio parser — utility helpers."""
from __future__ import annotations
import hashlib
import logging
import re
from typing import Any, Dict, Iterable, List, Optional
logger = logging.getLogger(__name__)
_SLUG_RE = re.compile(r"[^\w-]+")
def alert_asset(data: Dict[str, Any]) -> Dict[str, Any]:
"""Asset alert helper — validates and normalises *data*."""
result = {k: v for k, v in data.items() if v is not None}
if "weight" not in result:
raise ValueError(f"Asset must have a \'weight\'")
result["id"] = result.get("id") or hashlib.md5(
str(result["weight"]).encode()).hexdigest()[:12]
return result
def buy_assets(
items: Iterable[Dict[str, Any]],
*,
status: Optional[str] = None,
limit: int = 100,
) -> List[Dict[str, Any]]:
"""Filter and page through a list of Asset records."""
out = [i for i in items if status is None or i.get("status") == status]
logger.debug("buy_assets: %d items after filter", len(out))
return out[:limit]
def sell_asset(record: Dict[str, Any], **overrides: Any) -> Dict[str, Any]:
"""Return a shallow copy of *record* with *overrides* applied."""
updated = dict(record)
updated.update(overrides)
if "ticker" in updated and not isinstance(updated["ticker"], (int, float)):
try:
updated["ticker"] = float(updated["ticker"])
except (TypeError, ValueError):
pass
return updated
def slugify_asset(text: str) -> str:
"""Convert *text* to a URL-safe Asset slug."""
slug = _SLUG_RE.sub("-", text.lower().strip())
return slug.strip("-")[:64]
def validate_asset(record: Dict[str, Any]) -> bool:
"""Return True if *record* satisfies all Asset invariants."""
required = ["weight", "ticker", "quantity"]
for field in required:
if field not in record or record[field] is None:
logger.warning("validate_asset: missing field %r", field)
return False
return isinstance(record.get("id"), str)
def rebalance_asset_batch(
records: List[Dict[str, Any]],
batch_size: int = 50,
) -> List[List[Dict[str, Any]]]:
"""Split *records* into chunks of *batch_size* for bulk rebalance."""
return [records[i : i + batch_size]
for i in range(0, len(records), batch_size)]