418 lines
22 KiB
Python
418 lines
22 KiB
Python
"""Persistent manual portfolio ledger and target-weight trade planner."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
from contextlib import closing
|
|
from datetime import datetime, timezone
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
import sqlite3
|
|
import zipfile
|
|
from typing import Any
|
|
|
|
|
|
DEFAULT_BOOK = Path("data/portfolio/prime_thai_portfolio.sqlite3")
|
|
MAX_CASH_AMOUNT = 1_000_000_000_000.0
|
|
_EOD_FILE = re.compile(r"set-history_EOD_(\d{4}-\d{2}-\d{2})\.csv$", re.IGNORECASE)
|
|
_SYMBOL = re.compile(r"[A-Z0-9]{1,12}$")
|
|
|
|
|
|
def _connect(database: str | Path = DEFAULT_BOOK) -> sqlite3.Connection:
|
|
path = Path(database)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
connection = sqlite3.connect(path, timeout=10.0, isolation_level=None)
|
|
connection.row_factory = sqlite3.Row
|
|
connection.execute("PRAGMA foreign_keys = ON")
|
|
connection.executescript("""
|
|
CREATE TABLE IF NOT EXISTS cash_events (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
kind TEXT NOT NULL CHECK (kind IN ('deposit', 'withdrawal', 'dividend')),
|
|
amount REAL NOT NULL CHECK (amount > 0),
|
|
occurred_at TEXT NOT NULL,
|
|
note TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE TABLE IF NOT EXISTS trades (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
symbol TEXT NOT NULL,
|
|
side TEXT NOT NULL CHECK (side IN ('BUY', 'SELL')),
|
|
quantity INTEGER NOT NULL CHECK (quantity > 0),
|
|
price REAL NOT NULL CHECK (price > 0),
|
|
fees REAL NOT NULL DEFAULT 0 CHECK (fees >= 0),
|
|
occurred_at TEXT NOT NULL,
|
|
note TEXT NOT NULL DEFAULT '',
|
|
is_estimated INTEGER NOT NULL DEFAULT 0 CHECK (is_estimated IN (0, 1)),
|
|
is_void INTEGER NOT NULL DEFAULT 0 CHECK (is_void IN (0, 1)),
|
|
voided_at TEXT
|
|
);
|
|
CREATE TABLE IF NOT EXISTS price_marks (
|
|
symbol TEXT PRIMARY KEY,
|
|
as_of TEXT NOT NULL,
|
|
close REAL NOT NULL CHECK (close > 0)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS trades_symbol_id ON trades(symbol, id);
|
|
CREATE INDEX IF NOT EXISTS trades_time_id ON trades(occurred_at, id);
|
|
CREATE INDEX IF NOT EXISTS cash_events_time_id ON cash_events(occurred_at, id);
|
|
""")
|
|
# Existing local portfolio databases predate estimated signal trades.
|
|
columns = {str(row["name"]) for row in connection.execute("PRAGMA table_info(trades)")}
|
|
if "is_estimated" not in columns:
|
|
connection.execute("ALTER TABLE trades ADD COLUMN is_estimated INTEGER NOT NULL DEFAULT 0")
|
|
if "is_void" not in columns:
|
|
connection.execute("ALTER TABLE trades ADD COLUMN is_void INTEGER NOT NULL DEFAULT 0")
|
|
if "voided_at" not in columns:
|
|
connection.execute("ALTER TABLE trades ADD COLUMN voided_at TEXT")
|
|
return connection
|
|
|
|
|
|
def read_latest_eod_quotes(archive_path: str | Path) -> tuple[str, dict[str, float]]:
|
|
"""Read closes from the newest daily CSV in a SiamChart ZIP."""
|
|
path = Path(archive_path)
|
|
if not path.is_file():
|
|
raise FileNotFoundError(f"ไม่พบ ZIP EOD: {path}")
|
|
with zipfile.ZipFile(path) as archive:
|
|
candidates = [(match.group(1), member.filename)
|
|
for member in archive.infolist()
|
|
if (match := _EOD_FILE.search(Path(member.filename).name))]
|
|
if not candidates:
|
|
raise ValueError("ZIP ไม่มีไฟล์ SiamChart EOD รายวัน")
|
|
as_of, member_name = max(candidates, key=lambda item: item[0])
|
|
with archive.open(member_name) as binary:
|
|
import io
|
|
with io.TextIOWrapper(binary, encoding="utf-8-sig", newline="") as stream:
|
|
reader = csv.DictReader(stream)
|
|
required = {"<TICKER>", "<CLOSE>"}
|
|
if not required.issubset(set(reader.fieldnames or [])):
|
|
raise ValueError("คอลัมน์ในไฟล์ EOD ไม่ตรงกับรูปแบบที่รองรับ")
|
|
quotes: dict[str, float] = {}
|
|
for row in reader:
|
|
symbol = (row.get("<TICKER>") or "").strip().upper()
|
|
try:
|
|
close = float(row["<CLOSE>"])
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if symbol and math.isfinite(close) and close > 0:
|
|
quotes[symbol] = close
|
|
return as_of, quotes
|
|
|
|
|
|
def update_price_marks(as_of: str, quotes: dict[str, float], *,
|
|
database: str | Path = DEFAULT_BOOK) -> None:
|
|
with closing(_connect(database)) as connection:
|
|
connection.executemany("""
|
|
INSERT INTO price_marks(symbol, as_of, close) VALUES (?, ?, ?)
|
|
ON CONFLICT(symbol) DO UPDATE SET as_of=excluded.as_of, close=excluded.close
|
|
WHERE excluded.as_of >= price_marks.as_of
|
|
""", [(symbol.upper(), as_of, float(close)) for symbol, close in quotes.items()
|
|
if _SYMBOL.fullmatch(symbol.upper()) and math.isfinite(float(close)) and float(close) > 0])
|
|
|
|
|
|
def add_cash_event(kind: str, amount: float, note: str = "", *,
|
|
database: str | Path = DEFAULT_BOOK) -> int:
|
|
kind = kind.strip().lower()
|
|
if kind not in {"deposit", "withdrawal", "dividend"}:
|
|
raise ValueError("รายการเงินสดต้องเป็น deposit, withdrawal หรือ dividend")
|
|
value = float(amount)
|
|
if not math.isfinite(value) or value <= 0 or value > MAX_CASH_AMOUNT:
|
|
raise ValueError("จำนวนเงินต้องมากกว่า 0 และไม่เกิน 1,000,000,000,000 บาท")
|
|
with closing(_connect(database)) as connection:
|
|
cursor = connection.execute(
|
|
"INSERT INTO cash_events(kind, amount, occurred_at, note) VALUES (?, ?, ?, ?)",
|
|
(kind, value, datetime.now().astimezone().isoformat(), str(note)[:200]),
|
|
)
|
|
return int(cursor.lastrowid)
|
|
|
|
|
|
def _read_ledger(connection: sqlite3.Connection) -> tuple[list[sqlite3.Row], list[sqlite3.Row]]:
|
|
cash_events = connection.execute("SELECT * FROM cash_events ORDER BY id").fetchall()
|
|
trades = connection.execute("SELECT * FROM trades ORDER BY id").fetchall()
|
|
return cash_events, trades
|
|
|
|
|
|
def _calculate_book(cash_events: list[sqlite3.Row], trades: list[sqlite3.Row]) -> dict[str, Any]:
|
|
cash = 0.0
|
|
net_contributed = 0.0
|
|
deposits = 0
|
|
for event in cash_events:
|
|
amount = float(event["amount"])
|
|
if event["kind"] == "deposit":
|
|
cash += amount
|
|
net_contributed += amount
|
|
deposits += 1
|
|
elif event["kind"] == "withdrawal":
|
|
cash -= amount
|
|
net_contributed -= amount
|
|
elif event["kind"] == "dividend":
|
|
cash += amount
|
|
|
|
positions: dict[str, dict[str, float | int]] = {}
|
|
for trade in trades:
|
|
if "is_void" in trade.keys() and bool(trade["is_void"]):
|
|
continue
|
|
symbol = str(trade["symbol"])
|
|
position = positions.setdefault(symbol, {"quantity": 0, "cost_basis": 0.0, "realized_pnl": 0.0})
|
|
quantity = int(trade["quantity"])
|
|
price = float(trade["price"])
|
|
fees = float(trade["fees"])
|
|
gross = quantity * price
|
|
if trade["side"] == "BUY":
|
|
cash -= gross + fees
|
|
position["quantity"] = int(position["quantity"]) + quantity
|
|
position["cost_basis"] = float(position["cost_basis"]) + gross + fees
|
|
else:
|
|
held = int(position["quantity"])
|
|
average_cost = float(position["cost_basis"]) / held if held else 0.0
|
|
cash += gross - fees
|
|
position["realized_pnl"] = float(position["realized_pnl"]) + gross - fees - average_cost * quantity
|
|
position["cost_basis"] = max(0.0, float(position["cost_basis"]) - average_cost * quantity)
|
|
position["quantity"] = held - quantity
|
|
positions = {symbol: position for symbol, position in positions.items()
|
|
if int(position["quantity"]) > 0}
|
|
return {"cash": cash, "net_contributed": net_contributed,
|
|
"deposit_count": deposits, "positions": positions}
|
|
|
|
|
|
def record_trade(symbol: str, side: str, quantity: int, price: float, fees: float = 0.0,
|
|
note: str = "", *, estimated: bool = False,
|
|
database: str | Path = DEFAULT_BOOK) -> int:
|
|
symbol = symbol.strip().upper()
|
|
side = side.strip().upper()
|
|
if not _SYMBOL.fullmatch(symbol):
|
|
raise ValueError("รหัสหุ้นต้องเป็นตัวอักษร A-Z หรือตัวเลข 1–12 ตัว")
|
|
if side not in {"BUY", "SELL"}:
|
|
raise ValueError("ประเภทรายการต้องเป็น BUY หรือ SELL")
|
|
if isinstance(quantity, bool) or int(quantity) != quantity or int(quantity) <= 0:
|
|
raise ValueError("จำนวนหุ้นต้องเป็นจำนวนเต็มมากกว่า 0")
|
|
quantity = int(quantity)
|
|
price, fees = float(price), float(fees)
|
|
if not math.isfinite(price) or price <= 0 or not math.isfinite(fees) or fees < 0:
|
|
raise ValueError("ราคาต้องมากกว่า 0 และค่าธรรมเนียมต้องไม่ติดลบ")
|
|
|
|
with closing(_connect(database)) as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
cash_events, trades = _read_ledger(connection)
|
|
book = _calculate_book(cash_events, trades)
|
|
if side == "BUY" and quantity * price + fees > float(book["cash"]) + 0.005:
|
|
raise ValueError(f"เงินสดไม่พอ: มี {float(book['cash']):,.2f} บาท แต่รายการนี้ใช้ {quantity * price + fees:,.2f} บาท")
|
|
held = int(book["positions"].get(symbol, {}).get("quantity", 0))
|
|
if side == "SELL" and quantity > held:
|
|
raise ValueError(f"หุ้น {symbol} มี {held:,} หุ้น ขายเกินจำนวนที่บันทึกไว้ไม่ได้")
|
|
cursor = connection.execute(
|
|
"INSERT INTO trades(symbol, side, quantity, price, fees, occurred_at, note, is_estimated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
(symbol, side, quantity, price, fees, datetime.now().astimezone().isoformat(),
|
|
str(note)[:200], int(bool(estimated))),
|
|
)
|
|
connection.execute("COMMIT")
|
|
return int(cursor.lastrowid)
|
|
except Exception:
|
|
connection.execute("ROLLBACK")
|
|
raise
|
|
|
|
|
|
def update_trade(trade_id: int, quantity: int, price: float, fees: float = 0.0, *,
|
|
database: str | Path = DEFAULT_BOOK) -> None:
|
|
"""Edit a previously logged signal trade to match the actual fill."""
|
|
if isinstance(quantity, bool) or int(quantity) != quantity or int(quantity) <= 0:
|
|
raise ValueError("จำนวนหุ้นต้องเป็นจำนวนเต็มมากกว่า 0")
|
|
quantity = int(quantity)
|
|
price, fees = float(price), float(fees)
|
|
if not math.isfinite(price) or price <= 0 or not math.isfinite(fees) or fees < 0:
|
|
raise ValueError("ราคาต้องมากกว่า 0 และค่าธรรมเนียมต้องไม่ติดลบ")
|
|
|
|
with closing(_connect(database)) as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
cash_events, trades = _read_ledger(connection)
|
|
trade = next((row for row in trades if int(row["id"]) == int(trade_id)), None)
|
|
if trade is None or ("is_void" in trade.keys() and bool(trade["is_void"])):
|
|
raise ValueError("ไม่พบรายการที่แก้ไขได้ หรือรายการนี้ถูกยกเลิกแล้ว")
|
|
symbol, side = str(trade["symbol"]), str(trade["side"])
|
|
old_quantity, old_price, old_fees = int(trade["quantity"]), float(trade["price"]), float(trade["fees"])
|
|
book = _calculate_book(cash_events, trades)
|
|
held = int(book["positions"].get(symbol, {}).get("quantity", 0))
|
|
resulting_held = held + (quantity - old_quantity if side == "BUY" else old_quantity - quantity)
|
|
if resulting_held < 0:
|
|
raise ValueError(f"แก้จำนวนแล้วหุ้น {symbol} จะติดลบ; ตรวจรายการขายภายหลังด้วย")
|
|
if side == "BUY":
|
|
resulting_cash = float(book["cash"]) + old_quantity * old_price + old_fees - quantity * price - fees
|
|
else:
|
|
resulting_cash = float(book["cash"]) - old_quantity * old_price + old_fees + quantity * price - fees
|
|
if resulting_cash < -0.005:
|
|
raise ValueError(f"แก้รายการแล้วเงินสดจะติดลบ {abs(resulting_cash):,.2f} บาท")
|
|
connection.execute(
|
|
"UPDATE trades SET quantity=?, price=?, fees=?, is_estimated=0 WHERE id=?",
|
|
(quantity, price, fees, int(trade_id)),
|
|
)
|
|
connection.execute("COMMIT")
|
|
except Exception:
|
|
connection.execute("ROLLBACK")
|
|
raise
|
|
|
|
|
|
def void_trade(trade_id: int, *, database: str | Path = DEFAULT_BOOK) -> None:
|
|
"""Void a signal-estimated trade while preserving it in the audit ledger."""
|
|
with closing(_connect(database)) as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
cash_events, trades = _read_ledger(connection)
|
|
trade = next((row for row in trades if int(row["id"]) == int(trade_id)), None)
|
|
if (trade is None or ("is_void" in trade.keys() and bool(trade["is_void"]))
|
|
or not bool(trade["is_estimated"])):
|
|
raise ValueError("ยกเลิกได้เฉพาะรายการประมาณการจากสัญญาณที่ยังไม่ถูกยกเลิก")
|
|
book = _calculate_book(cash_events, trades)
|
|
symbol, side = str(trade["symbol"]), str(trade["side"])
|
|
quantity, price, fees = int(trade["quantity"]), float(trade["price"]), float(trade["fees"])
|
|
held = int(book["positions"].get(symbol, {}).get("quantity", 0))
|
|
resulting_held = held - quantity if side == "BUY" else held + quantity
|
|
resulting_cash = float(book["cash"]) + (quantity * price + fees if side == "BUY"
|
|
else -quantity * price + fees)
|
|
if resulting_held < 0:
|
|
raise ValueError(f"ยกเลิกแล้วหุ้น {symbol} จะติดลบ; แก้รายการขายภายหลังก่อน")
|
|
if resulting_cash < -0.005:
|
|
raise ValueError(f"ยกเลิกแล้วเงินสดจะติดลบ {abs(resulting_cash):,.2f} บาท")
|
|
connection.execute(
|
|
"UPDATE trades SET is_void=1, voided_at=? WHERE id=?",
|
|
(datetime.now().astimezone().isoformat(), int(trade_id)),
|
|
)
|
|
connection.execute("COMMIT")
|
|
except Exception:
|
|
connection.execute("ROLLBACK")
|
|
raise
|
|
|
|
|
|
def portfolio_view(signals: list[dict[str, str]], *, board_lot: int = 100,
|
|
signal_as_of: str | None = None,
|
|
database: str | Path = DEFAULT_BOOK) -> dict[str, Any]:
|
|
if board_lot <= 0:
|
|
raise ValueError("board_lot must be positive")
|
|
with closing(_connect(database)) as connection:
|
|
cash_events, trades = _read_ledger(connection)
|
|
book = _calculate_book(cash_events, trades)
|
|
price_rows = connection.execute("SELECT symbol, as_of, close FROM price_marks").fetchall()
|
|
recent_cash = connection.execute("SELECT * FROM cash_events ORDER BY id DESC LIMIT 10").fetchall()
|
|
recent_trades = connection.execute("SELECT * FROM trades ORDER BY id DESC LIMIT 10").fetchall()
|
|
|
|
prices = {str(row["symbol"]): {"as_of": str(row["as_of"]), "close": float(row["close"])}
|
|
for row in price_rows}
|
|
targets: dict[str, dict[str, float | str]] = {}
|
|
for signal in signals:
|
|
symbol = str(signal.get("symbol", "")).strip().upper()
|
|
try:
|
|
weight = float(signal.get("target_weight", "0"))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if symbol and weight > 0:
|
|
targets[symbol] = {"weight": weight, "source_model": str(signal.get("source_model", ""))}
|
|
|
|
positions: dict[str, dict[str, float | int]] = book["positions"]
|
|
missing_prices = sorted(symbol for symbol in positions if symbol not in prices)
|
|
signal_as_of = signal_as_of or max(
|
|
(str(row.get("signal_as_of", "")) for row in signals), default=""
|
|
) or max((price["as_of"] for price in prices.values()), default="")
|
|
quote_as_of = max((price["as_of"] for price in prices.values()), default="")
|
|
signal_quote_mismatch = bool(signal_as_of and quote_as_of and signal_as_of != quote_as_of)
|
|
stale_prices = sorted(symbol for symbol in positions
|
|
if symbol in prices and signal_as_of and prices[symbol]["as_of"] < signal_as_of)
|
|
incomplete_symbols = sorted(set(missing_prices) | set(stale_prices))
|
|
complete = not incomplete_symbols and not signal_quote_mismatch
|
|
total_market_value = 0.0
|
|
for symbol, position in positions.items():
|
|
if symbol in prices:
|
|
total_market_value += int(position["quantity"]) * prices[symbol]["close"]
|
|
cash = float(book["cash"])
|
|
equity = cash + total_market_value
|
|
account_exists = int(book["deposit_count"]) > 0 or bool(positions)
|
|
rows: list[dict[str, Any]] = []
|
|
buy_value = 0.0
|
|
sell_value = 0.0
|
|
for symbol in sorted(set(targets) | set(positions)):
|
|
target = targets.get(symbol, {"weight": 0.0, "source_model": ""})
|
|
mark = prices.get(symbol)
|
|
quantity = int(positions.get(symbol, {}).get("quantity", 0))
|
|
cost_basis = float(positions.get(symbol, {}).get("cost_basis", 0.0))
|
|
realized_pnl = float(positions.get(symbol, {}).get("realized_pnl", 0.0))
|
|
close = float(mark["close"]) if mark else None
|
|
target_value = equity * float(target["weight"]) if account_exists and complete else None
|
|
target_quantity = (int(math.floor(float(target_value) / close / board_lot + 1e-10) * board_lot)
|
|
if close and account_exists and complete and target_value is not None else None)
|
|
delta = (int(target_quantity) - quantity) if target_quantity is not None else None
|
|
market_value = quantity * close if close is not None else None
|
|
average_cost = cost_basis / quantity if quantity else None
|
|
unrealized = market_value - cost_basis if market_value is not None else None
|
|
if mark is None or symbol in stale_prices:
|
|
action = "PRICE NEEDED" if quantity else "WAIT"
|
|
elif not complete and account_exists:
|
|
action = "REVIEW"
|
|
elif not account_exists:
|
|
action = "WAIT"
|
|
elif float(target["weight"]) > 0 and target_quantity == 0 and quantity == 0:
|
|
action = "BELOW LOT"
|
|
elif delta is not None and delta > 0:
|
|
action = "BUY"
|
|
buy_value += delta * close # type: ignore[operator]
|
|
elif delta is not None and delta < 0:
|
|
action = "SELL"
|
|
sell_value += -delta * close # type: ignore[operator]
|
|
else:
|
|
action = "HOLD"
|
|
rows.append({
|
|
"symbol": symbol,
|
|
"source_model": str(target["source_model"]),
|
|
"target_weight": float(target["weight"]),
|
|
"quantity_held": quantity,
|
|
"target_quantity": target_quantity,
|
|
"delta_quantity": delta if action in {"BUY", "SELL"} else 0,
|
|
"action": action,
|
|
"reference_close": close,
|
|
"suggested_limit_price": close,
|
|
"price_as_of": str(mark["as_of"]) if mark else None,
|
|
"market_value": market_value,
|
|
"target_value": target_value,
|
|
"average_cost": average_cost,
|
|
"unrealized_pnl": unrealized,
|
|
"realized_pnl": realized_pnl,
|
|
})
|
|
action_order = {"SELL": 0, "BUY": 1, "PRICE NEEDED": 2, "REVIEW": 3,
|
|
"BELOW LOT": 4, "HOLD": 5, "WAIT": 6}
|
|
rows.sort(key=lambda row: (action_order.get(row["action"], 9), row["symbol"]))
|
|
|
|
ledger: list[dict[str, Any]] = []
|
|
for event in recent_cash:
|
|
ledger.append({"kind": event["kind"], "amount": float(event["amount"]),
|
|
"occurred_at": event["occurred_at"], "note": event["note"]})
|
|
for trade in recent_trades:
|
|
ledger.append({"kind": trade["side"], "symbol": trade["symbol"],
|
|
"id": int(trade["id"]),
|
|
"quantity": int(trade["quantity"]), "price": float(trade["price"]),
|
|
"fees": float(trade["fees"]), "occurred_at": trade["occurred_at"],
|
|
"note": trade["note"],
|
|
"is_estimated": bool(trade["is_estimated"]),
|
|
"is_void": bool(trade["is_void"]),
|
|
"voided_at": trade["voided_at"]})
|
|
ledger.sort(key=lambda row: str(row["occurred_at"]), reverse=True)
|
|
|
|
net_contributed = float(book["net_contributed"])
|
|
return {
|
|
"account_exists": account_exists,
|
|
"deposit_count": int(book["deposit_count"]),
|
|
"cash": cash,
|
|
"net_contributed": net_contributed,
|
|
"market_value": total_market_value,
|
|
"equity": equity,
|
|
"profit_loss": equity - net_contributed if complete else None,
|
|
"profit_loss_pct": (equity / net_contributed - 1.0) if complete and net_contributed > 0 else None,
|
|
"complete": complete,
|
|
"unpriced_symbols": missing_prices,
|
|
"stale_price_symbols": stale_prices,
|
|
"signal_quote_mismatch": signal_quote_mismatch,
|
|
"price_as_of": quote_as_of or None,
|
|
"buy_value": buy_value,
|
|
"sell_value": sell_value,
|
|
"cash_after_planned_trades": cash + sell_value - buy_value,
|
|
"requires_sell_proceeds": max(0.0, buy_value - cash),
|
|
"rows": rows,
|
|
"ledger": ledger[:10],
|
|
}
|