|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Work out which corporate action multiplied a holding's share count. |
| 4 | +
|
| 5 | +Order history keeps the share counts as they were on the day. A split or bonus multiplies |
| 6 | +what you hold without any transaction recording it, so the tradebook ends up showing more |
| 7 | +shares sold than were ever bought. FIFO cannot match those sales against anything, so the |
| 8 | +ticker is dropped from booked profit entirely — which is safe, and on this portfolio hid a |
| 9 | +third of it. |
| 10 | +
|
| 11 | +A split leaves fingerprints, and this solves for the only ratio that fits all of them: |
| 12 | +
|
| 13 | + * after adjusting, FIFO never runs short of shares; |
| 14 | + * the final share count equals what the broker says is held; |
| 15 | + * the remaining shares' average cost matches the broker's own average. |
| 16 | +
|
| 17 | +The last one is what makes this trustworthy rather than arithmetic that happens to close. |
| 18 | +The broker's average is computed independently of anything here, so a wrong ratio has to |
| 19 | +agree with a number it never saw. |
| 20 | +
|
| 21 | + python3 app/splits.py propose ratios, write nothing |
| 22 | + python3 app/splits.py --write add the unambiguous ones to config.json |
| 23 | +
|
| 24 | +NOTHING is applied without --write, and even then only where exactly one ratio fits. A |
| 25 | +wrong ratio silently rewrites realised profit, and unlike a missing figure a wrong one |
| 26 | +does not announce itself. |
| 27 | +""" |
| 28 | +import os, sys, json, datetime as dt |
| 29 | + |
| 30 | +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 31 | +import db as D |
| 32 | +import config as CFG |
| 33 | + |
| 34 | +# Ratios seen in Indian corporate actions: 1:1 bonus is 2x, 1:2 bonus 1.5x, and so on. |
| 35 | +RATIOS = [1.5, 2, 2.5, 3, 4, 5, 6, 8, 10, 20, 50, 100] |
| 36 | +AVG_TOLERANCE = 0.05 # broker's average cost must agree within 5% |
| 37 | + |
| 38 | + |
| 39 | +def _rows(c, ticker): |
| 40 | + return list(c.execute( |
| 41 | + "SELECT date,type,quantity,price FROM transactions WHERE ticker=?" |
| 42 | + " ORDER BY date,id", (ticker,))) |
| 43 | + |
| 44 | + |
| 45 | +def replay(rows, events): |
| 46 | + """FIFO with `events` applied. -> (ok, held_quantity, remaining_cost). |
| 47 | +
|
| 48 | + ok is False the moment a sale exceeds the shares on hand, which is the signal that |
| 49 | + the ratio being tried is wrong (or that there is no ratio). |
| 50 | + """ |
| 51 | + lots, applied = [], 0 |
| 52 | + for r in rows: |
| 53 | + while applied < len(events) and events[applied]["date"] <= r["date"]: |
| 54 | + f = events[applied]["ratio"] |
| 55 | + for lot in lots: |
| 56 | + lot[0] *= f |
| 57 | + lot[1] /= f |
| 58 | + applied += 1 |
| 59 | + q, px = r["quantity"] or 0.0, r["price"] or 0.0 |
| 60 | + if r["type"] == "buy": |
| 61 | + lots.append([q, px]) |
| 62 | + continue |
| 63 | + if r["type"] != "sell": |
| 64 | + continue |
| 65 | + need = q |
| 66 | + while need > 1e-6 and lots: |
| 67 | + take = min(need, lots[0][0]) |
| 68 | + lots[0][0] -= take |
| 69 | + need -= take |
| 70 | + if lots[0][0] <= 1e-6: |
| 71 | + lots.pop(0) |
| 72 | + if need > 1e-6: |
| 73 | + return False, 0.0, 0.0 |
| 74 | + # A split can fall after the last trade in a ticker — you stop trading it, then it |
| 75 | + # splits. Those events never come up in the loop above, so apply them here or the |
| 76 | + # final share count will not match what the broker reports and the right ratio gets |
| 77 | + # rejected as wrong. |
| 78 | + while applied < len(events): |
| 79 | + f = events[applied]["ratio"] |
| 80 | + for lot in lots: |
| 81 | + lot[0] *= f |
| 82 | + lot[1] /= f |
| 83 | + applied += 1 |
| 84 | + return True, sum(l[0] for l in lots), sum(l[0] * l[1] for l in lots) |
| 85 | + |
| 86 | + |
| 87 | +def infer(rows, held_qty, broker_avg): |
| 88 | + """-> (ratios_that_fit, candidate_dates). One ratio means it is safe to use.""" |
| 89 | + if not any(r["type"] == "buy" for r in rows): |
| 90 | + return [], [] |
| 91 | + dates = sorted({r["date"] for r in rows}) |
| 92 | + hits = [] |
| 93 | + for i, sd in enumerate(dates): |
| 94 | + for ratio in RATIOS: |
| 95 | + ok, q, cost = replay(rows, [{"date": sd, "ratio": ratio}]) |
| 96 | + if not ok or abs(q - held_qty) > 0.01: |
| 97 | + continue |
| 98 | + if held_qty > 0 and broker_avg: |
| 99 | + avg = cost / q |
| 100 | + if abs(avg - broker_avg) / broker_avg > AVG_TOLERANCE: |
| 101 | + continue |
| 102 | + hits.append((sd, ratio)) |
| 103 | + return sorted({r for _, r in hits}), sorted({d for d, _ in hits}) |
| 104 | + |
| 105 | + |
| 106 | +def unmatched(c): |
| 107 | + """Tickers whose sales exceed their purchases — the ones FIFO has to skip.""" |
| 108 | + out = [] |
| 109 | + for r in c.execute("SELECT DISTINCT ticker FROM transactions ORDER BY ticker"): |
| 110 | + t = r["ticker"] |
| 111 | + rows = _rows(c, t) |
| 112 | + ok, _, _ = replay(rows, []) |
| 113 | + if not ok: |
| 114 | + out.append(t) |
| 115 | + return out |
| 116 | + |
| 117 | + |
| 118 | +def main(): |
| 119 | + write = "--write" in sys.argv |
| 120 | + c = D.connect() |
| 121 | + pos = {r["ticker"]: (r["quantity"], r["avg_cost"]) for r in |
| 122 | + c.execute("SELECT ticker,quantity,avg_cost FROM positions")} |
| 123 | + known = CFG.splits() |
| 124 | + |
| 125 | + todo = [t for t in unmatched(c) if t not in known] |
| 126 | + if not todo: |
| 127 | + print("every holding's sales match its purchases — nothing to infer.") |
| 128 | + return 0 |
| 129 | + |
| 130 | + print(f"{len(todo)} holding(s) sell more shares than they bought.\n" |
| 131 | + "That is what a split or bonus looks like in order history.\n") |
| 132 | + found, ambiguous, none = {}, [], [] |
| 133 | + for t in todo: |
| 134 | + rows = _rows(c, t) |
| 135 | + q, avg = pos.get(t, (0.0, None)) |
| 136 | + ratios, dates = infer(rows, q, avg) |
| 137 | + if len(ratios) == 1: |
| 138 | + # earliest date that works — a split cannot precede the shares it multiplied |
| 139 | + found[t] = {"date": dates[0], "ratio": ratios[0]} |
| 140 | + check = "and the broker's average cost agrees" if q > 0 else \ |
| 141 | + "share count closes exactly (nothing held, so no average to check)" |
| 142 | + print(f" {t:<13} {ratios[0]:g}x on or before {dates[0]} {check}") |
| 143 | + elif ratios: |
| 144 | + ambiguous.append((t, ratios)) |
| 145 | + else: |
| 146 | + none.append(t) |
| 147 | + |
| 148 | + if ambiguous: |
| 149 | + print(f"\n {len(ambiguous)} ambiguous — several ratios fit equally well, so" |
| 150 | + " picking one would be a guess:") |
| 151 | + for t, rs in ambiguous: |
| 152 | + print(f" {t:<13} could be {', '.join(f'{r:g}x' for r in rs)}") |
| 153 | + if none: |
| 154 | + print(f"\n {len(none)} unexplained by any single ratio — most likely two" |
| 155 | + " corporate actions,\n a merger with an odd conversion, or purchases" |
| 156 | + " missing from the tradebook:") |
| 157 | + print(" " + ", ".join(none)) |
| 158 | + |
| 159 | + if not found: |
| 160 | + print("\nnothing unambiguous to write.") |
| 161 | + return 0 |
| 162 | + if not write: |
| 163 | + print(f"\n{len(found)} ratio(s) determined. Nothing written — re-run with --write" |
| 164 | + " to add them\nto config.json, or add them by hand if you would rather" |
| 165 | + " check each first.") |
| 166 | + return 0 |
| 167 | + |
| 168 | + path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), |
| 169 | + "config.json") |
| 170 | + cfg = json.load(open(path)) if os.path.exists(path) else {} |
| 171 | + cfg.setdefault("splits", {}) |
| 172 | + for t, ev in found.items(): |
| 173 | + cfg["splits"][t] = [ev] |
| 174 | + with open(path, "w") as fh: |
| 175 | + json.dump(cfg, fh, indent=2) |
| 176 | + fh.write("\n") |
| 177 | + CFG.load(reload=True) |
| 178 | + print(f"\nwrote {len(found)} split(s) to config.json.") |
| 179 | + print("Re-check them against the corporate action if a figure looks wrong; removing" |
| 180 | + " an entry\nputs the holding back to being skipped, which is the safe state.") |
| 181 | + return 0 |
| 182 | + |
| 183 | + |
| 184 | +if __name__ == "__main__": |
| 185 | + sys.exit(main()) |
0 commit comments