pm-ledger 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pm_ledger/__init__.py +18 -0
- pm_ledger/__main__.py +4 -0
- pm_ledger/cli.py +90 -0
- pm_ledger/export.py +77 -0
- pm_ledger/fifo.py +123 -0
- pm_ledger/ledger.py +106 -0
- pm_ledger/model.py +90 -0
- pm_ledger/parsers/__init__.py +79 -0
- pm_ledger/parsers/generic_csv.py +36 -0
- pm_ledger/parsers/kalshi_activity.py +108 -0
- pm_ledger/parsers/kalshi_pnl.py +62 -0
- pm_ledger/parsers/polymarket_us.py +132 -0
- pm_ledger/summary.py +107 -0
- pm_ledger/util.py +190 -0
- pm_ledger-0.1.0.dist-info/METADATA +141 -0
- pm_ledger-0.1.0.dist-info/RECORD +20 -0
- pm_ledger-0.1.0.dist-info/WHEEL +5 -0
- pm_ledger-0.1.0.dist-info/entry_points.txt +2 -0
- pm_ledger-0.1.0.dist-info/licenses/LICENSE +21 -0
- pm_ledger-0.1.0.dist-info/top_level.txt +1 -0
pm_ledger/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""pm_ledger: a local, offline ledger for prediction-market (event-contract) trade exports.
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
|
|
5
|
+
Privacy: this package makes no network calls. It reads files you give it and writes files where you tell it.
|
|
6
|
+
"""
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
SCHEMA_VERSION = "1.0"
|
|
9
|
+
DISCLAIMER = ("Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. "
|
|
10
|
+
"Record-keeping tool, not tax, legal, or investment advice.")
|
|
11
|
+
PRIVACY = ("Your data stays on your own computer. pm_ledger makes no network calls, has no telemetry or analytics, "
|
|
12
|
+
"and never sends your trades anywhere.")
|
|
13
|
+
|
|
14
|
+
from .model import LedgerEvent, ClosedLot, OpenLot # noqa: E402
|
|
15
|
+
from .parsers import parse_file, parse_text, detect # noqa: E402
|
|
16
|
+
from .fifo import match_fifo # noqa: E402
|
|
17
|
+
from .ledger import Ledger # noqa: E402
|
|
18
|
+
from .summary import year_summary # noqa: E402
|
pm_ledger/__main__.py
ADDED
pm_ledger/cli.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""pm-ledger command line. Offline: reads your files, writes your files, no network.
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
|
|
5
|
+
Examples:
|
|
6
|
+
pm-ledger detect Kalshi-Recent-Activity-All.csv
|
|
7
|
+
pm-ledger summarize realized_pnl_2026.csv polymarket_us_activities.json --year 2026
|
|
8
|
+
pm-ledger export *.csv *.json --format csv --out ledger_out/
|
|
9
|
+
pm-ledger export polymarket_us_activities.json --format sheet --out polymarket_for_sheet.csv
|
|
10
|
+
pm-ledger positions Kalshi-Recent-Activity-All.csv
|
|
11
|
+
pm-ledger import FILE... --store ledger.json (idempotent, re-run safely)
|
|
12
|
+
"""
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
from . import DISCLAIMER, PRIVACY, __version__
|
|
19
|
+
from .ledger import Ledger
|
|
20
|
+
from .parsers import detect
|
|
21
|
+
from .summary import year_summary
|
|
22
|
+
from . import export
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _ledger(args):
|
|
26
|
+
led = Ledger.load(args.store, args.tz) if getattr(args, "store", None) and os.path.exists(args.store) else Ledger(args.tz)
|
|
27
|
+
for f in args.files:
|
|
28
|
+
r = led.import_file(f, dedupe=not args.no_dedupe)
|
|
29
|
+
print(f"imported {os.path.basename(f)} as {r['kind']}: {r['added']} added, {r['skipped_duplicates']} duplicates skipped",
|
|
30
|
+
file=sys.stderr)
|
|
31
|
+
for w in r["warnings"]:
|
|
32
|
+
print(" warning:", w, file=sys.stderr)
|
|
33
|
+
return led
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv=None):
|
|
37
|
+
p = argparse.ArgumentParser(prog="pm-ledger", description=f"pm_ledger {__version__}. {DISCLAIMER} {PRIVACY}")
|
|
38
|
+
p.add_argument("--tz", default="ET", help="ET (default), CT, MT, PT, AZ, AK, HI or UTC")
|
|
39
|
+
p.add_argument("--no-dedupe", action="store_true", help="keep identical Kalshi trade rows (see docs)")
|
|
40
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
41
|
+
d = sub.add_parser("detect"); d.add_argument("files", nargs="+")
|
|
42
|
+
i = sub.add_parser("import"); i.add_argument("files", nargs="+"); i.add_argument("--store", required=True)
|
|
43
|
+
sm = sub.add_parser("summarize"); sm.add_argument("files", nargs="*"); sm.add_argument("--year", type=int, required=True)
|
|
44
|
+
sm.add_argument("--store"); sm.add_argument("--json", action="store_true")
|
|
45
|
+
ex = sub.add_parser("export"); ex.add_argument("files", nargs="*"); ex.add_argument("--store")
|
|
46
|
+
ex.add_argument("--format", choices=["json", "csv", "sheet"], default="json"); ex.add_argument("--out", required=True)
|
|
47
|
+
ex.add_argument("--year", type=int)
|
|
48
|
+
ex.add_argument("--venues", default="polymarket_us", help="for --format sheet: comma list, e.g. polymarket_us,kalshi")
|
|
49
|
+
po = sub.add_parser("positions"); po.add_argument("files", nargs="*"); po.add_argument("--store")
|
|
50
|
+
args = p.parse_args(argv)
|
|
51
|
+
|
|
52
|
+
if args.cmd == "detect":
|
|
53
|
+
for f in args.files:
|
|
54
|
+
with open(f, encoding="utf-8-sig") as fh:
|
|
55
|
+
print(f"{f}\t{detect(fh.read())}")
|
|
56
|
+
return 0
|
|
57
|
+
led = _ledger(args)
|
|
58
|
+
if args.cmd == "import":
|
|
59
|
+
led.save(args.store); print(f"saved {args.store}: {len(led.events)} events, {len(led.venue_lots)} venue lots")
|
|
60
|
+
elif args.cmd == "summarize":
|
|
61
|
+
closed, open_lots, warns = led.compute()
|
|
62
|
+
summ = year_summary(closed, open_lots, led.cash_events(), args.year, args.tz)
|
|
63
|
+
if args.json:
|
|
64
|
+
print(json.dumps(summ, indent=1))
|
|
65
|
+
else:
|
|
66
|
+
r = summ["realized"]
|
|
67
|
+
print(f"Tax year {args.year} ({args.tz})\n closed lots {r['lots']}, markets {r['markets_closed']}, win rate "
|
|
68
|
+
f"{'' if r['win_rate'] is None else round(r['win_rate'] * 100, 1)}%\n gross ${r['gross_pnl_usd']} fees ${r['fees_usd']} "
|
|
69
|
+
f"net ${r['net_pnl_usd']}")
|
|
70
|
+
for v, b in summ["by_venue"].items():
|
|
71
|
+
print(f" {v}: net ${b['net_pnl_usd']} over {b['lots']} lots")
|
|
72
|
+
print(" " + summ["scenarios"]["note"])
|
|
73
|
+
print(" " + DISCLAIMER)
|
|
74
|
+
elif args.cmd == "export":
|
|
75
|
+
if args.format == "json":
|
|
76
|
+
print(export.write_json(led, args.out))
|
|
77
|
+
elif args.format == "csv":
|
|
78
|
+
for f in export.write_csvs(led, args.out, args.year):
|
|
79
|
+
print(f)
|
|
80
|
+
else:
|
|
81
|
+
print(export.write_sheet(led, args.out, tuple(args.venues.split(","))))
|
|
82
|
+
elif args.cmd == "positions":
|
|
83
|
+
_, open_lots, _ = led.compute()
|
|
84
|
+
for l in open_lots:
|
|
85
|
+
print(f"{l.venue}\t{l.market_key}\t{l.side}\t{l.qty}\t@{l.entry_price_usd}\tcost ${l.cost_basis_usd}")
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
sys.exit(main())
|
pm_ledger/export.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Writers: JSON ledger document and CSV files (including the sheet-ready lot file for the Prediction Market Trade Ledger workbook).
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
"""
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
from .util import to_local, parse_iso, dec, s
|
|
10
|
+
|
|
11
|
+
EVENT_COLS = ["id", "venue", "account_alias", "event_type", "ts_utc", "ts_local", "market_key", "market_ticker", "market_title", "side",
|
|
12
|
+
"action", "qty", "price_usd", "fee_usd", "cash_flow_usd", "result", "category", "source_kind", "source_file", "source_row"]
|
|
13
|
+
LOT_COLS = ["lot_id", "venue", "account_alias", "market_key", "market_ticker", "market_title", "category", "side", "qty", "open_ts_utc",
|
|
14
|
+
"close_ts_utc", "close_local_date", "tax_year", "holding_days", "term", "entry_price_usd", "exit_price_usd", "open_fees_usd",
|
|
15
|
+
"close_fees_usd", "cost_basis_usd", "proceeds_usd", "pnl_gross_usd", "pnl_net_usd", "close_type", "matched_by", "source_kind",
|
|
16
|
+
"source_file", "source_row"]
|
|
17
|
+
OPEN_COLS = ["venue", "account_alias", "market_key", "market_ticker", "market_title", "category", "side", "qty", "open_ts_utc",
|
|
18
|
+
"entry_price_usd", "open_fees_usd", "cost_basis_usd"]
|
|
19
|
+
CASH_COLS = ["ts_utc", "ts_local", "venue", "account_alias", "event_type", "cash_flow_usd", "fee_usd", "source_kind", "source_file", "source_row"]
|
|
20
|
+
SHEET_COLS = ["opened", "closed", "market", "ticker", "side", "qty", "entry_price_usd", "exit_price_usd", "fees_usd", "venue"]
|
|
21
|
+
VENUE_LABEL = {"polymarket_us": "Polymarket US", "kalshi": "Kalshi"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _write(path, cols, rows):
|
|
25
|
+
with open(path, "w", newline="") as fh:
|
|
26
|
+
w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore")
|
|
27
|
+
w.writeheader()
|
|
28
|
+
for r in rows:
|
|
29
|
+
w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in cols})
|
|
30
|
+
return path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def write_json(ledger, path):
|
|
34
|
+
with open(path, "w") as fh:
|
|
35
|
+
json.dump(ledger.to_document(), fh, indent=1)
|
|
36
|
+
return path
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def write_csvs(ledger, outdir, year=None):
|
|
40
|
+
os.makedirs(outdir, exist_ok=True)
|
|
41
|
+
closed, open_lots, _ = ledger.compute()
|
|
42
|
+
if year:
|
|
43
|
+
closed = [l for l in closed if l.tax_year == int(year)]
|
|
44
|
+
evs = sorted(ledger.events.values(), key=lambda e: e.ts_utc or "")
|
|
45
|
+
return [
|
|
46
|
+
_write(os.path.join(outdir, "ledger_events.csv"), EVENT_COLS, [e.to_dict() for e in evs]),
|
|
47
|
+
_write(os.path.join(outdir, "closed_lots.csv"), LOT_COLS, [l.to_dict() for l in closed]),
|
|
48
|
+
_write(os.path.join(outdir, "open_lots.csv"), OPEN_COLS, [l.to_dict() for l in open_lots]),
|
|
49
|
+
_write(os.path.join(outdir, "cashflows.csv"), CASH_COLS, [e.to_dict() for e in evs if e.event_type not in ("fill", "settlement")]),
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _local(ts, zone):
|
|
54
|
+
return to_local(parse_iso(ts), zone).strftime("%Y-%m-%d %H:%M:%S") if ts else ""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def sheet_rows(ledger, venues=("polymarket_us",)):
|
|
58
|
+
"""Rows for the workbook's 'Import Polymarket US + Other' tab: closed lots plus open lots (closed/exit blank). Column 10 = venue."""
|
|
59
|
+
closed, open_lots, _ = ledger.compute()
|
|
60
|
+
rows = []
|
|
61
|
+
for l in closed:
|
|
62
|
+
if l.venue in venues:
|
|
63
|
+
rows.append({"opened": _local(l.open_ts_utc, ledger.zone), "closed": _local(l.close_ts_utc, ledger.zone),
|
|
64
|
+
"market": l.market_title or l.market_key, "ticker": l.market_key, "side": l.side, "qty": l.qty,
|
|
65
|
+
"entry_price_usd": l.entry_price_usd, "exit_price_usd": l.exit_price_usd,
|
|
66
|
+
"fees_usd": s(dec(l.open_fees_usd) + dec(l.close_fees_usd)), "venue": VENUE_LABEL.get(l.venue, l.venue)})
|
|
67
|
+
for l in open_lots:
|
|
68
|
+
if l.venue in venues:
|
|
69
|
+
rows.append({"opened": _local(l.open_ts_utc, ledger.zone), "closed": "", "market": l.market_title or l.market_key,
|
|
70
|
+
"ticker": l.market_key, "side": l.side, "qty": l.qty, "entry_price_usd": l.entry_price_usd,
|
|
71
|
+
"exit_price_usd": "", "fees_usd": l.open_fees_usd, "venue": VENUE_LABEL.get(l.venue, l.venue)})
|
|
72
|
+
rows.sort(key=lambda r: (r["closed"] == "", r["closed"] or r["opened"]))
|
|
73
|
+
return rows
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def write_sheet(ledger, path, venues=("polymarket_us",)):
|
|
77
|
+
return _write(path, SHEET_COLS, sheet_rows(ledger, venues))
|
pm_ledger/fifo.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""FIFO lot matching over normalized LedgerEvents.
|
|
2
|
+
|
|
3
|
+
Rules (see docs/LEDGER-SPEC.md):
|
|
4
|
+
- Lots are grouped by (venue, account_alias, market_key).
|
|
5
|
+
- A buy opens a lot at price_usd; its fee is the lot's open fee (prorated if the lot is split later).
|
|
6
|
+
- A sell closes the oldest lots of the same side first (FIFO) at price_usd; its fee is prorated over the closed quantity.
|
|
7
|
+
- Kalshi netting: on Kalshi a buy of the opposite side while holding a position closes that position
|
|
8
|
+
(buying NO at p is selling YES at 1-p). Remaining quantity opens a new lot.
|
|
9
|
+
- A settlement closes every open lot in the market at $1 (lot side == result) or $0 (otherwise). If the venue reports
|
|
10
|
+
more contracts than the ledger holds (trades outside the imported range), a lot is created for the gap at the venue's
|
|
11
|
+
average price with an unknown open date, and a warning is raised.
|
|
12
|
+
|
|
13
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
14
|
+
"""
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
|
|
17
|
+
from .model import ClosedLot, OpenLot
|
|
18
|
+
from .util import dec, s, parse_iso, to_local, event_id, ZERO, categorize
|
|
19
|
+
|
|
20
|
+
NETTING_VENUES = {"kalshi"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _Lot:
|
|
24
|
+
__slots__ = ("side", "qty", "left", "price", "fee", "ts", "src")
|
|
25
|
+
|
|
26
|
+
def __init__(self, side, qty, price, fee, ts, src):
|
|
27
|
+
self.side, self.qty, self.left, self.price, self.fee, self.ts, self.src = side, qty, qty, price, fee, ts, src
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _order(e):
|
|
31
|
+
rank = {"fill": 0, "settlement": 1}.get(e.event_type, 2)
|
|
32
|
+
return (e.ts_utc or "", rank, 0 if e.action == "buy" else 1, e.source_row or 0)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def match_fifo(events, zone="ET"):
|
|
36
|
+
"""Return (closed_lots, open_lots, warnings) from fills and settlements."""
|
|
37
|
+
books = defaultdict(list)
|
|
38
|
+
meta = {}
|
|
39
|
+
closed, warns = [], []
|
|
40
|
+
for e in sorted((e for e in events if e.event_type in ("fill", "settlement") and e.market_key), key=_order):
|
|
41
|
+
key = (e.venue, e.account_alias, e.market_key)
|
|
42
|
+
meta.setdefault(key, (e.market_ticker, e.market_title, e.category))
|
|
43
|
+
book = books[key]
|
|
44
|
+
qty, price, fee = dec(e.qty), dec(e.price_usd), dec(e.fee_usd)
|
|
45
|
+
ts = parse_iso(e.ts_utc)
|
|
46
|
+
|
|
47
|
+
def close(lot, take, exit_price, close_fee_total, close_qty_total, ctype):
|
|
48
|
+
ofee = lot.fee * take / lot.qty if lot.qty else ZERO
|
|
49
|
+
cfee = close_fee_total * take / close_qty_total if close_qty_total else ZERO
|
|
50
|
+
gross = take * (exit_price - lot.price)
|
|
51
|
+
hold = (ts - lot.ts).total_seconds() / 86400 if lot.ts else None
|
|
52
|
+
loc = to_local(ts, zone)
|
|
53
|
+
fp = f"{key}|{lot.src}|{e.id}|{take}"
|
|
54
|
+
tk, title, cat = meta[key]
|
|
55
|
+
closed.append(ClosedLot(
|
|
56
|
+
lot_id=event_id(e.venue, "fifo|" + fp), venue=e.venue, market_key=e.market_key, side=lot.side, qty=s(take),
|
|
57
|
+
open_ts_utc=lot.ts.strftime("%Y-%m-%dT%H:%M:%SZ") if lot.ts else None, close_ts_utc=e.ts_utc,
|
|
58
|
+
entry_price_usd=s(lot.price), exit_price_usd=s(exit_price), open_fees_usd=s(ofee), close_fees_usd=s(cfee),
|
|
59
|
+
cost_basis_usd=s(take * lot.price + ofee), proceeds_usd=s(take * exit_price - cfee), pnl_gross_usd=s(gross),
|
|
60
|
+
pnl_net_usd=s(gross - ofee - cfee), close_type=ctype, matched_by="pm_ledger_fifo", account_alias=e.account_alias,
|
|
61
|
+
market_ticker=tk, market_title=title, category=cat or categorize(e.market_key, title),
|
|
62
|
+
close_local_date=loc.strftime("%Y-%m-%d"), tax_year=loc.year,
|
|
63
|
+
holding_days=round(hold, 4) if hold is not None else None,
|
|
64
|
+
term=("long" if hold > 365 else "short") if hold is not None else "unknown",
|
|
65
|
+
source_kind=e.source_kind, source_file=e.source_file, source_row=e.source_row))
|
|
66
|
+
lot.left -= take
|
|
67
|
+
|
|
68
|
+
if e.event_type == "settlement":
|
|
69
|
+
held = {sd: sum(l.left for l in book if l.side == sd) for sd in ("YES", "NO")}
|
|
70
|
+
if e.side in held and qty > held[e.side]:
|
|
71
|
+
gap = qty - held[e.side]
|
|
72
|
+
avg = dec((e.raw or {}).get("avg_price_usd")) if (e.raw or {}).get("avg_price_usd") else (
|
|
73
|
+
dec((e.raw or {}).get("cost")) / qty if (e.raw or {}).get("cost") else ZERO)
|
|
74
|
+
book.insert(0, _Lot(e.side, gap, avg, ZERO, None, e.id + "|gap"))
|
|
75
|
+
warns.append(f"{e.venue} {e.market_key}: settlement shows {qty} {e.side} contracts but the ledger held "
|
|
76
|
+
f"{held[e.side]}; added a lot for {gap} at the venue's average price ${s(avg)} (open date unknown)")
|
|
77
|
+
win = e.result
|
|
78
|
+
for lot in book:
|
|
79
|
+
if lot.left > 0 and (e.side is None or lot.side == e.side or (e.raw or {}).get("both")):
|
|
80
|
+
exit_price = dec(1) if win == lot.side else (price if win is None else ZERO)
|
|
81
|
+
close(lot, lot.left, exit_price, ZERO, ZERO, "settlement")
|
|
82
|
+
books[key] = [l for l in book if l.left > 0]
|
|
83
|
+
continue
|
|
84
|
+
|
|
85
|
+
side = e.side or "YES"
|
|
86
|
+
if e.action == "sell":
|
|
87
|
+
need = qty
|
|
88
|
+
for lot in book:
|
|
89
|
+
if need <= 0:
|
|
90
|
+
break
|
|
91
|
+
if lot.side == side and lot.left > 0:
|
|
92
|
+
take = min(lot.left, need)
|
|
93
|
+
close(lot, take, price, fee, qty, "sale")
|
|
94
|
+
need -= take
|
|
95
|
+
if need > 0:
|
|
96
|
+
warns.append(f"{e.venue} {e.market_key}: sold {s(need)} more {side} contracts than held; excess ignored "
|
|
97
|
+
"(import the earlier trades to fix)")
|
|
98
|
+
else:
|
|
99
|
+
opp = "NO" if side == "YES" else "YES"
|
|
100
|
+
remaining = qty
|
|
101
|
+
if e.venue in NETTING_VENUES and any(l.side == opp and l.left > 0 for l in book):
|
|
102
|
+
for lot in book:
|
|
103
|
+
if remaining <= 0:
|
|
104
|
+
break
|
|
105
|
+
if lot.side == opp and lot.left > 0:
|
|
106
|
+
take = min(lot.left, remaining)
|
|
107
|
+
close(lot, take, dec(1) - price, fee, qty, "sale")
|
|
108
|
+
remaining -= take
|
|
109
|
+
if remaining > 0:
|
|
110
|
+
open_fee = fee * remaining / qty if qty else ZERO
|
|
111
|
+
book.append(_Lot(side, remaining, price, open_fee, ts, e.id))
|
|
112
|
+
books[key] = [l for l in book if l.left > 0]
|
|
113
|
+
|
|
114
|
+
open_lots = []
|
|
115
|
+
for key, book in books.items():
|
|
116
|
+
tk, title, cat = meta[key]
|
|
117
|
+
for l in book:
|
|
118
|
+
ofee = l.fee * l.left / l.qty if l.qty else ZERO
|
|
119
|
+
open_lots.append(OpenLot(venue=key[0], account_alias=key[1], market_key=key[2], side=l.side, qty=s(l.left),
|
|
120
|
+
entry_price_usd=s(l.price), open_fees_usd=s(ofee), cost_basis_usd=s(l.left * l.price + ofee),
|
|
121
|
+
open_ts_utc=l.ts.strftime("%Y-%m-%dT%H:%M:%SZ") if l.ts else None, market_ticker=tk,
|
|
122
|
+
market_title=title, category=cat or categorize(key[2], title)))
|
|
123
|
+
return closed, open_lots, warns
|
pm_ledger/ledger.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Ledger: an idempotent, local store of events and venue-matched lots, plus the combined lot view.
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
from . import __version__, SCHEMA_VERSION, DISCLAIMER, PRIVACY
|
|
10
|
+
from .model import LedgerEvent, ClosedLot
|
|
11
|
+
from .fifo import match_fifo
|
|
12
|
+
from .parsers import parse_file, parse_text
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Ledger:
|
|
16
|
+
def __init__(self, zone="ET"):
|
|
17
|
+
self.zone = zone
|
|
18
|
+
self.events = {}
|
|
19
|
+
self.venue_lots = {}
|
|
20
|
+
self.journal = []
|
|
21
|
+
self.sources = []
|
|
22
|
+
self.warnings = []
|
|
23
|
+
|
|
24
|
+
# ---- ingest -------------------------------------------------------
|
|
25
|
+
def add_result(self, res):
|
|
26
|
+
added = skipped = 0
|
|
27
|
+
for e in res.events:
|
|
28
|
+
if e.id in self.events:
|
|
29
|
+
skipped += 1
|
|
30
|
+
else:
|
|
31
|
+
self.events[e.id] = e; added += 1
|
|
32
|
+
for l in res.lots:
|
|
33
|
+
if l.lot_id in self.venue_lots:
|
|
34
|
+
skipped += 1
|
|
35
|
+
else:
|
|
36
|
+
self.venue_lots[l.lot_id] = l; added += 1
|
|
37
|
+
self.sources.append({"file": res.source_file, "kind": res.kind, "added": added, "skipped_duplicates": skipped})
|
|
38
|
+
self.warnings.extend(res.warnings)
|
|
39
|
+
return {"kind": res.kind, "file": res.source_file, "added": added, "skipped_duplicates": skipped, "warnings": res.warnings}
|
|
40
|
+
|
|
41
|
+
def import_file(self, path, venue_hint=None, dedupe=True, account_alias="default"):
|
|
42
|
+
return self.add_result(parse_file(path, venue_hint, dedupe, self.zone, account_alias))
|
|
43
|
+
|
|
44
|
+
def import_text(self, text, name=None, venue_hint=None, dedupe=True, account_alias="default"):
|
|
45
|
+
return self.add_result(parse_text(text, name, venue_hint, dedupe, self.zone, account_alias))
|
|
46
|
+
|
|
47
|
+
def append_events(self, events):
|
|
48
|
+
added = 0
|
|
49
|
+
for e in events:
|
|
50
|
+
ev = e if isinstance(e, LedgerEvent) else LedgerEvent(**e)
|
|
51
|
+
if ev.id not in self.events:
|
|
52
|
+
self.events[ev.id] = ev; added += 1
|
|
53
|
+
return {"added": added, "skipped_duplicates": len(events) - added}
|
|
54
|
+
|
|
55
|
+
# ---- views --------------------------------------------------------
|
|
56
|
+
def compute(self):
|
|
57
|
+
"""Combined closed lots, open lots and warnings.
|
|
58
|
+
|
|
59
|
+
Kalshi: where the official P&L file covers a tax year, its lots (Kalshi's own FIFO) are used for that year and
|
|
60
|
+
activity-derived Kalshi lots for the same year are dropped, so nothing is double counted.
|
|
61
|
+
"""
|
|
62
|
+
events = list(self.events.values())
|
|
63
|
+
fifo_closed, open_lots, warns = match_fifo(events, self.zone)
|
|
64
|
+
venue_years = {(l.venue, l.account_alias, l.tax_year) for l in self.venue_lots.values()}
|
|
65
|
+
closed = list(self.venue_lots.values()) + [l for l in fifo_closed if (l.venue, l.account_alias, l.tax_year) not in venue_years]
|
|
66
|
+
closed.sort(key=lambda l: (l.close_ts_utc or "", l.market_key))
|
|
67
|
+
return closed, open_lots, warns
|
|
68
|
+
|
|
69
|
+
def cash_events(self):
|
|
70
|
+
return [e for e in self.events.values() if e.event_type not in ("fill", "settlement")]
|
|
71
|
+
|
|
72
|
+
# ---- persistence ---------------------------------------------------
|
|
73
|
+
def to_document(self, include_raw=False):
|
|
74
|
+
closed, open_lots, warns = self.compute()
|
|
75
|
+
evs = []
|
|
76
|
+
for e in sorted(self.events.values(), key=lambda e: (e.ts_utc or "", e.id)):
|
|
77
|
+
d = e.to_dict()
|
|
78
|
+
if not include_raw:
|
|
79
|
+
d["raw"] = {}
|
|
80
|
+
evs.append(d)
|
|
81
|
+
return {"schema_version": SCHEMA_VERSION, "generator": f"pm_ledger {__version__}",
|
|
82
|
+
"generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "time_zone": self.zone,
|
|
83
|
+
"disclaimer": DISCLAIMER, "privacy": PRIVACY, "sources": self.sources, "events": evs,
|
|
84
|
+
"closed_lots": [l.to_dict() for l in closed], "open_lots": [l.to_dict() for l in open_lots],
|
|
85
|
+
"journal": self.journal, "warnings": self.warnings + warns}
|
|
86
|
+
|
|
87
|
+
def save(self, path):
|
|
88
|
+
doc = self.to_document(include_raw=True)
|
|
89
|
+
doc["venue_lots"] = [l.to_dict() for l in self.venue_lots.values()]
|
|
90
|
+
tmp = path + ".tmp"
|
|
91
|
+
with open(tmp, "w") as fh:
|
|
92
|
+
json.dump(doc, fh, indent=1)
|
|
93
|
+
os.replace(tmp, path)
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def load(cls, path, zone=None):
|
|
97
|
+
with open(path) as fh:
|
|
98
|
+
doc = json.load(fh)
|
|
99
|
+
led = cls(zone or doc.get("time_zone", "ET"))
|
|
100
|
+
for e in doc.get("events", []):
|
|
101
|
+
ev = LedgerEvent(**e); led.events[ev.id] = ev
|
|
102
|
+
for l in doc.get("venue_lots", []):
|
|
103
|
+
lot = ClosedLot(**l); led.venue_lots[lot.lot_id] = lot
|
|
104
|
+
led.journal = doc.get("journal", [])
|
|
105
|
+
led.sources = doc.get("sources", [])
|
|
106
|
+
return led
|
pm_ledger/model.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Data model: LedgerEvent, ClosedLot, OpenLot (mirrors schema/ledger.schema.json).
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
"""
|
|
5
|
+
from dataclasses import dataclass, field, asdict
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
EVENT_TYPES = ("fill", "settlement", "fee", "deposit", "withdrawal", "interest", "credit", "rebate")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class LedgerEvent:
|
|
13
|
+
id: str
|
|
14
|
+
venue: str # "kalshi" | "polymarket_us" | other
|
|
15
|
+
event_type: str # one of EVENT_TYPES
|
|
16
|
+
ts_utc: Optional[str]
|
|
17
|
+
ts_local: Optional[str] = None
|
|
18
|
+
account_alias: str = "default"
|
|
19
|
+
market_key: Optional[str] = None # ticker, slug, or cleaned title (what FIFO groups on)
|
|
20
|
+
market_ticker: Optional[str] = None
|
|
21
|
+
market_title: Optional[str] = None
|
|
22
|
+
side: Optional[str] = None # "YES" | "NO"
|
|
23
|
+
action: Optional[str] = None # "buy" | "sell" (fills only)
|
|
24
|
+
qty: str = "0"
|
|
25
|
+
price_usd: Optional[str] = None
|
|
26
|
+
fee_usd: str = "0.00"
|
|
27
|
+
cash_flow_usd: str = "0.00"
|
|
28
|
+
result: Optional[str] = None # settlements: winning side "YES" | "NO"
|
|
29
|
+
category: Optional[str] = None
|
|
30
|
+
source_kind: Optional[str] = None
|
|
31
|
+
source_file: Optional[str] = None
|
|
32
|
+
source_row: Optional[int] = None
|
|
33
|
+
raw: dict = field(default_factory=dict)
|
|
34
|
+
|
|
35
|
+
def to_dict(self):
|
|
36
|
+
return asdict(self)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class ClosedLot:
|
|
41
|
+
lot_id: str
|
|
42
|
+
venue: str
|
|
43
|
+
market_key: str
|
|
44
|
+
side: str
|
|
45
|
+
qty: str
|
|
46
|
+
open_ts_utc: Optional[str]
|
|
47
|
+
close_ts_utc: str
|
|
48
|
+
entry_price_usd: str
|
|
49
|
+
exit_price_usd: str
|
|
50
|
+
open_fees_usd: str
|
|
51
|
+
close_fees_usd: str
|
|
52
|
+
cost_basis_usd: str
|
|
53
|
+
proceeds_usd: str
|
|
54
|
+
pnl_gross_usd: str
|
|
55
|
+
pnl_net_usd: str
|
|
56
|
+
close_type: str # "settlement" | "sale"
|
|
57
|
+
matched_by: str # "venue_fifo" (Kalshi P&L file) | "pm_ledger_fifo"
|
|
58
|
+
account_alias: str = "default"
|
|
59
|
+
market_ticker: Optional[str] = None
|
|
60
|
+
market_title: Optional[str] = None
|
|
61
|
+
category: Optional[str] = None
|
|
62
|
+
close_local_date: Optional[str] = None
|
|
63
|
+
tax_year: Optional[int] = None
|
|
64
|
+
holding_days: Optional[float] = None
|
|
65
|
+
term: Optional[str] = None # "short" | "long" | "unknown"
|
|
66
|
+
source_kind: Optional[str] = None
|
|
67
|
+
source_file: Optional[str] = None
|
|
68
|
+
source_row: Optional[int] = None
|
|
69
|
+
|
|
70
|
+
def to_dict(self):
|
|
71
|
+
return asdict(self)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class OpenLot:
|
|
76
|
+
venue: str
|
|
77
|
+
market_key: str
|
|
78
|
+
side: str
|
|
79
|
+
qty: str
|
|
80
|
+
entry_price_usd: str
|
|
81
|
+
open_fees_usd: str
|
|
82
|
+
cost_basis_usd: str
|
|
83
|
+
open_ts_utc: Optional[str]
|
|
84
|
+
account_alias: str = "default"
|
|
85
|
+
market_ticker: Optional[str] = None
|
|
86
|
+
market_title: Optional[str] = None
|
|
87
|
+
category: Optional[str] = None
|
|
88
|
+
|
|
89
|
+
def to_dict(self):
|
|
90
|
+
return asdict(self)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Format detection and dispatch.
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
"""
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from . import kalshi_pnl, kalshi_activity, polymarket_us, generic_csv
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ParseResult:
|
|
14
|
+
def __init__(self, kind, events=None, lots=None, warnings=None, source_file=None):
|
|
15
|
+
self.kind = kind
|
|
16
|
+
self.events = events or []
|
|
17
|
+
self.lots = lots or [] # venue-matched closed lots (Kalshi P&L file)
|
|
18
|
+
self.warnings = warnings or []
|
|
19
|
+
self.source_file = source_file
|
|
20
|
+
|
|
21
|
+
def to_dict(self):
|
|
22
|
+
return {"kind": self.kind, "source_file": self.source_file, "events": len(self.events),
|
|
23
|
+
"venue_lots": len(self.lots), "warnings": self.warnings}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _header(text):
|
|
27
|
+
first = text.lstrip("\ufeff").splitlines()[0] if text.strip() else ""
|
|
28
|
+
return [h.strip().strip('"').strip() for h in next(csv.reader([first]))] if first else []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def detect(text):
|
|
32
|
+
"""Return 'kalshi_pnl' | 'kalshi_activity' | 'polymarket_us_json' | 'pm_ledger_events' | 'unknown'."""
|
|
33
|
+
t = text.lstrip("\ufeff").lstrip()
|
|
34
|
+
if t.startswith("{") or t.startswith("["):
|
|
35
|
+
try:
|
|
36
|
+
data = json.loads(t)
|
|
37
|
+
except ValueError:
|
|
38
|
+
data = None
|
|
39
|
+
if data is not None and polymarket_us.looks_like(data):
|
|
40
|
+
return "polymarket_us_json"
|
|
41
|
+
if data is not None:
|
|
42
|
+
return "unknown"
|
|
43
|
+
if t and all(line.strip().startswith("{") for line in t.splitlines()[:3] if line.strip()):
|
|
44
|
+
return "polymarket_us_json" if polymarket_us.looks_like([json.loads(l) for l in t.splitlines()[:3] if l.strip()]) else "unknown"
|
|
45
|
+
hdr = set(h.lower() for h in _header(t))
|
|
46
|
+
if {"quantity_fp", "market_ticker", "realized_pnl_with_fees_dollars"} <= hdr:
|
|
47
|
+
return "kalshi_pnl"
|
|
48
|
+
if {"type", "market_title", "price_in_cents", "traded_time"} <= hdr:
|
|
49
|
+
return "kalshi_activity"
|
|
50
|
+
if {"venue", "event_type", "ts_utc", "qty"} <= hdr:
|
|
51
|
+
return "pm_ledger_events"
|
|
52
|
+
return "unknown"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_text(text, source_file=None, venue_hint=None, dedupe=True, zone="ET", account_alias="default"):
|
|
56
|
+
kind = detect(text)
|
|
57
|
+
if kind == "unknown" and venue_hint:
|
|
58
|
+
kind = {"kalshi": "kalshi_activity", "polymarket_us": "polymarket_us_json"}.get(venue_hint, kind)
|
|
59
|
+
name = os.path.basename(source_file) if source_file else None
|
|
60
|
+
if kind == "kalshi_pnl":
|
|
61
|
+
lots, events, warns = kalshi_pnl.parse(text, name, zone, account_alias)
|
|
62
|
+
return ParseResult(kind, events, lots, warns, name)
|
|
63
|
+
if kind == "kalshi_activity":
|
|
64
|
+
events, warns = kalshi_activity.parse(text, name, dedupe, zone, account_alias)
|
|
65
|
+
return ParseResult(kind, events, [], warns, name)
|
|
66
|
+
if kind == "polymarket_us_json":
|
|
67
|
+
events, warns = polymarket_us.parse(text, name, zone, account_alias)
|
|
68
|
+
return ParseResult(kind, events, [], warns, name)
|
|
69
|
+
if kind == "pm_ledger_events":
|
|
70
|
+
events, warns = generic_csv.parse(text, name)
|
|
71
|
+
return ParseResult(kind, events, [], warns, name)
|
|
72
|
+
raise ValueError("Could not recognise this file. Supported: Kalshi realized_pnl_*.csv, Kalshi-Recent-Activity-*.csv, "
|
|
73
|
+
"Polymarket US /v1/portfolio/activities JSON, pm_ledger ledger_events.csv")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def parse_file(path, venue_hint=None, dedupe=True, zone="ET", account_alias="default"):
|
|
77
|
+
with open(path, "r", encoding="utf-8-sig", newline="") as fh:
|
|
78
|
+
text = fh.read()
|
|
79
|
+
return parse_text(text, path, venue_hint, dedupe, zone, account_alias)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Round-trip parser for pm_ledger's own ledger_events.csv template (any venue, including manual entries).
|
|
2
|
+
|
|
3
|
+
Not affiliated with, endorsed by, or sponsored by Kalshi or Polymarket. Record-keeping tool, not tax, legal, or investment advice.
|
|
4
|
+
"""
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
|
|
8
|
+
from ..model import LedgerEvent, EVENT_TYPES
|
|
9
|
+
from ..util import dec, s, parse_iso, iso_utc, iso_local, event_id, categorize
|
|
10
|
+
|
|
11
|
+
COLUMNS = ["id", "venue", "account_alias", "event_type", "ts_utc", "market_key", "market_ticker", "market_title", "side", "action",
|
|
12
|
+
"qty", "price_usd", "fee_usd", "cash_flow_usd", "result", "category"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse(text, source_file=None):
|
|
16
|
+
rdr = csv.DictReader(io.StringIO(text.lstrip("\ufeff")))
|
|
17
|
+
events, warns = [], []
|
|
18
|
+
for i, r in enumerate(rdr, start=2):
|
|
19
|
+
r = {k: (v or "").strip() for k, v in r.items() if k}
|
|
20
|
+
if not r.get("event_type"):
|
|
21
|
+
continue
|
|
22
|
+
if r["event_type"] not in EVENT_TYPES:
|
|
23
|
+
warns.append(f"row {i}: unknown event_type {r['event_type']!r}"); continue
|
|
24
|
+
ts = parse_iso(r.get("ts_utc"))
|
|
25
|
+
fp = "|".join(r.get(c, "") for c in COLUMNS[1:])
|
|
26
|
+
events.append(LedgerEvent(id=r.get("id") or event_id(r.get("venue") or "other", "csv|" + fp), venue=r.get("venue") or "other",
|
|
27
|
+
event_type=r["event_type"], ts_utc=iso_utc(ts), ts_local=iso_local(ts), account_alias=r.get("account_alias") or "default",
|
|
28
|
+
market_key=r.get("market_key") or r.get("market_ticker") or r.get("market_title") or None,
|
|
29
|
+
market_ticker=r.get("market_ticker") or None, market_title=r.get("market_title") or None,
|
|
30
|
+
side=(r.get("side") or "").upper() or None, action=(r.get("action") or "").lower() or None,
|
|
31
|
+
qty=s(dec(r.get("qty"))), price_usd=s(dec(r.get("price_usd"))) if r.get("price_usd") else None,
|
|
32
|
+
fee_usd=s(dec(r.get("fee_usd"))), cash_flow_usd=s(dec(r.get("cash_flow_usd"))),
|
|
33
|
+
result=(r.get("result") or "").upper() or None,
|
|
34
|
+
category=r.get("category") or categorize(r.get("market_key"), r.get("market_title")),
|
|
35
|
+
source_kind="pm_ledger_events", source_file=source_file, source_row=i, raw={}))
|
|
36
|
+
return events, warns
|