s-ttp commited on
Commit
b71e2fd
·
verified ·
1 Parent(s): ae54610

History tab: rebalance-by-rebalance record and every position, from Alpaca's orders

Browse files
Files changed (5) hide show
  1. app.py +29 -3
  2. qt3/broker.py +18 -2
  3. qt3/history.py +87 -0
  4. static/index.html +123 -10
  5. tests/test_qt3_space.py +25 -0
app.py CHANGED
@@ -1,7 +1,7 @@
1
  """Updraft (the Quality-Trend 3 strategy) — automated monthly strategy on an Alpaca paper account, with a public live page.
2
 
3
  Public (read-only): GET /, /api/health, /api/status, /api/portfolio, /api/performance, /api/orders,
4
- /api/ranking, /api/plan (dry-run of what a rebalance would do now).
5
  Private: POST /api/rebalance?dry=0 and POST /api/refresh with header X-Rebalance-Token: <REBALANCE_TOKEN>.
6
  The Space schedules itself (qt3/scheduler.py: a 15-minute tick that rebuilds the ranking daily and attempts the
7
  guarded rebalance on weekdays 10:00-15:30 New York); an outside cron calling /api/rebalance is optional. Either
@@ -19,7 +19,7 @@ from fastapi.responses import FileResponse
19
  from fastapi.staticfiles import StaticFiles
20
  from starlette.concurrency import run_in_threadpool
21
 
22
- from qt3 import config, performance, ranking, rebalance, scheduler
23
  from qt3.broker import Alpaca, BrokerError
24
 
25
 
@@ -127,6 +127,32 @@ async def orders():
127
  raise HTTPException(502, str(e))
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  @app.get("/api/status")
131
  async def status():
132
  def load():
@@ -177,5 +203,5 @@ async def run_rebalance(dry: int = 1, force: int = 0, x_rebalance_token: str = H
177
  except (BrokerError, ValueError) as e:
178
  raise HTTPException(502, f"rebalance failed: {e}")
179
  if out.get("executed"):
180
- _cache.clear()
181
  return {"dry_run": False, **out}
 
1
  """Updraft (the Quality-Trend 3 strategy) — automated monthly strategy on an Alpaca paper account, with a public live page.
2
 
3
  Public (read-only): GET /, /api/health, /api/status, /api/portfolio, /api/performance, /api/orders,
4
+ /api/history (rebalance by rebalance), /api/ranking, /api/plan (dry-run of what a rebalance would do now).
5
  Private: POST /api/rebalance?dry=0 and POST /api/refresh with header X-Rebalance-Token: <REBALANCE_TOKEN>.
6
  The Space schedules itself (qt3/scheduler.py: a 15-minute tick that rebuilds the ranking daily and attempts the
7
  guarded rebalance on weekdays 10:00-15:30 New York); an outside cron calling /api/rebalance is optional. Either
 
19
  from fastapi.staticfiles import StaticFiles
20
  from starlette.concurrency import run_in_threadpool
21
 
22
+ from qt3 import config, history, performance, ranking, rebalance, scheduler
23
  from qt3.broker import Alpaca, BrokerError
24
 
25
 
 
127
  raise HTTPException(502, str(e))
128
 
129
 
130
+ _names: dict = {}
131
+
132
+
133
+ @app.get("/api/history")
134
+ async def get_history():
135
+ def load():
136
+ a = broker()
137
+ orders, pos = a.all_orders(), a.positions()
138
+ flows = {}
139
+ for f in a.cash_flows():
140
+ flows[f["date"]] = flows.get(f["date"], 0.0) + f["amount"]
141
+ syms = {o["symbol"] for o in orders if str(o.get("client_order_id", "")).startswith(config.TAG + "-")}
142
+ rk = {r["ticker"]: r.get("name") for r in (ranking.cached() or {}).get("ranked", [])}
143
+ missing = sorted(s for s in syms if s not in _names and not rk.get(s))
144
+ if missing: # company names from Alpaca, once per symbol
145
+ try:
146
+ _names.update({s: v.get("name") for s, v in a.assets(missing).items()})
147
+ except BrokerError:
148
+ pass
149
+ return history.build(orders, pos, flows, {s: rk.get(s) or _names.get(s) for s in syms})
150
+ try:
151
+ return await run_in_threadpool(cached, "history", 300, load)
152
+ except BrokerError as e:
153
+ raise HTTPException(502, str(e))
154
+
155
+
156
  @app.get("/api/status")
157
  async def status():
158
  def load():
 
203
  except (BrokerError, ValueError) as e:
204
  raise HTTPException(502, f"rebalance failed: {e}")
205
  if out.get("executed"):
206
+ _cache.clear() # portfolio, performance and history show the new trades at once
207
  return {"dry_run": False, **out}
qt3/broker.py CHANGED
@@ -63,12 +63,27 @@ class Alpaca:
63
  def trading_days(self, start: date, end: date) -> list[str]:
64
  return [d["date"] for d in self._req("GET", "/v2/calendar", params={"start": str(start), "end": str(end)})]
65
 
66
- def orders(self, after: Optional[datetime] = None, status: str = "all", limit: int = 500) -> list[dict]:
 
67
  p = {"status": status, "limit": limit, "direction": "desc"}
68
  if after:
69
  p["after"] = after.astimezone(timezone.utc).isoformat()
 
 
70
  return self._req("GET", "/v2/orders", params=p)
71
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def order(self, oid: str) -> dict:
73
  return self._req("GET", f"/v2/orders/{oid}")
74
 
@@ -76,7 +91,8 @@ class Alpaca:
76
  out = {}
77
  for s in sorted(set(symbols)):
78
  a = self._req("GET", f"/v2/assets/{s}")
79
- out[s] = {"tradable": bool(a.get("tradable")), "fractionable": bool(a.get("fractionable"))}
 
80
  return out
81
 
82
  def latest_prices(self, symbols: list[str]) -> dict[str, float]:
 
63
  def trading_days(self, start: date, end: date) -> list[str]:
64
  return [d["date"] for d in self._req("GET", "/v2/calendar", params={"start": str(start), "end": str(end)})]
65
 
66
+ def orders(self, after: Optional[datetime] = None, status: str = "all", limit: int = 500,
67
+ until: Optional[str] = None) -> list[dict]:
68
  p = {"status": status, "limit": limit, "direction": "desc"}
69
  if after:
70
  p["after"] = after.astimezone(timezone.utc).isoformat()
71
+ if until:
72
+ p["until"] = until
73
  return self._req("GET", "/v2/orders", params=p)
74
 
75
+ def all_orders(self, status: str = "all") -> list[dict]:
76
+ """Every order, newest first (pages of 500 back in time)."""
77
+ out, seen, until = [], set(), None
78
+ while True:
79
+ page = self.orders(status=status, until=until)
80
+ new = [o for o in page if o["id"] not in seen]
81
+ seen.update(o["id"] for o in new)
82
+ out += new
83
+ if len(page) < 500 or not new:
84
+ return out
85
+ until = page[-1]["submitted_at"]
86
+
87
  def order(self, oid: str) -> dict:
88
  return self._req("GET", f"/v2/orders/{oid}")
89
 
 
91
  out = {}
92
  for s in sorted(set(symbols)):
93
  a = self._req("GET", f"/v2/assets/{s}")
94
+ out[s] = {"tradable": bool(a.get("tradable")), "fractionable": bool(a.get("fractionable")),
95
+ "name": a.get("name")}
96
  return out
97
 
98
  def latest_prices(self, symbols: list[str]) -> dict[str, float]:
qt3/history.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebalance history, built only from Alpaca's own orders — so it always matches the account.
2
+
3
+ Every order the strategy places carries client_order_id "qt3-YYYYMMDD-SYMBOL-side"; the date is the rebalance it
4
+ belongs to. Replaying the fills rebalance by rebalance gives what was bought (new names), sold (names that left the
5
+ portfolio) and kept (re-split to a third each), and each position's result: money taken out (sales, plus today's
6
+ value if still held) over money put in, so top-ups and trims are counted.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from datetime import date
11
+ from itertools import groupby
12
+
13
+ from . import config
14
+
15
+ EPS = 1e-6
16
+
17
+
18
+ def fills(orders: list[dict]) -> list[dict]:
19
+ out = []
20
+ for o in orders:
21
+ cid = str(o.get("client_order_id", ""))
22
+ parts = cid.split("-")
23
+ q, px = float(o.get("filled_qty") or 0), o.get("filled_avg_price")
24
+ if not cid.startswith(config.TAG + "-") or len(parts) < 4 or q <= 0 or not px:
25
+ continue
26
+ d = parts[1]
27
+ out.append({"rebalance": f"{d[:4]}-{d[4:6]}-{d[6:8]}", "at": o.get("filled_at") or o.get("submitted_at") or "",
28
+ "symbol": o["symbol"], "side": o["side"], "qty": q, "value": q * float(px)})
29
+ return sorted(out, key=lambda f: (f["rebalance"], f["at"]))
30
+
31
+
32
+ def build(orders: list[dict], positions: dict[str, dict], flows: dict[str, float] | None = None,
33
+ names: dict[str, str] | None = None) -> dict:
34
+ """positions: symbol → {"market_value": $} now. flows: date → net deposit. names: symbol → company name."""
35
+ flows, names = flows or {}, names or {}
36
+ qty: dict[str, float] = {}
37
+ open_: dict[str, dict] = {}
38
+ closed, events, prev = [], [], None
39
+ for reb, grp in groupby(fills(orders), key=lambda f: f["rebalance"]):
40
+ before = {s for s, q in qty.items() if q > EPS}
41
+ traded: dict[str, float] = {}
42
+ for f in grp:
43
+ buy = f["side"] == "buy"
44
+ s = f["symbol"]
45
+ qty[s] = qty.get(s, 0.0) + (f["qty"] if buy else -f["qty"])
46
+ p = open_.setdefault(s, {"symbol": s, "entered": reb, "put_in": 0.0, "taken_out": 0.0})
47
+ p["put_in" if buy else "taken_out"] += f["value"]
48
+ traded[s] = traded.get(s, 0.0) + (f["value"] if buy else -f["value"])
49
+ after = {s for s, q in qty.items() if q > EPS}
50
+ sold = []
51
+ for s in sorted(before - after):
52
+ p = open_.pop(s)
53
+ qty.pop(s, None)
54
+ row = {**p, "exited": reb, "days": (date.fromisoformat(reb) - date.fromisoformat(p["entered"])).days,
55
+ "pnl": round(p["taken_out"] - p["put_in"], 2),
56
+ "return": p["taken_out"] / p["put_in"] - 1 if p["put_in"] else None}
57
+ closed.append(row)
58
+ sold.append(row)
59
+ kept = sorted(before & after)
60
+ added = sum(v for d, v in flows.items() if prev and prev < d <= reb)
61
+ events.append({"date": reb, "first": prev is None, "bought": sorted(after - before), "sold": sold, "kept": kept,
62
+ "resplit": [{"symbol": s, "value": round(traded[s], 2)} for s in kept if abs(traded.get(s, 0)) >= 1],
63
+ "traded": round(sum(abs(v) for v in traded.values()), 2), "added": round(added, 2),
64
+ "holdings": sorted(after)})
65
+ prev = reb
66
+ today = date.today().isoformat()
67
+ still = []
68
+ for s, p in sorted(open_.items()):
69
+ now = float((positions.get(s) or {}).get("market_value") or 0)
70
+ out = p["taken_out"] + now
71
+ still.append({**p, "exited": None, "days": (date.fromisoformat(today) - date.fromisoformat(p["entered"])).days,
72
+ "value_now": round(now, 2), "pnl": round(out - p["put_in"], 2),
73
+ "return": out / p["put_in"] - 1 if p["put_in"] else None})
74
+ for row in closed + still:
75
+ row["name"] = names.get(row["symbol"])
76
+ row["put_in"], row["taken_out"] = round(row["put_in"], 2), round(row["taken_out"], 2)
77
+ rets = [c["return"] for c in closed if c["return"] is not None]
78
+ swaps = [len(e["bought"]) for e in events if not e["first"]]
79
+ return {"events": events[::-1], "closed": closed[::-1], "open": still,
80
+ "pending_deposits": round(sum(v for d, v in flows.items() if prev and d > prev), 2),
81
+ "summary": {"rebalances": len(events), "first": events[0]["date"] if events else None,
82
+ "swaps_per_rebalance": sum(swaps) / len(swaps) if swaps else None,
83
+ "closed": len(closed), "win_rate": sum(r > 0 for r in rets) / len(rets) if rets else None,
84
+ "avg_return": sum(rets) / len(rets) if rets else None,
85
+ "best": max(closed, key=lambda c: c["return"] or -9, default=None),
86
+ "worst": min(closed, key=lambda c: c["return"] or 9, default=None),
87
+ "avg_days": sum(c["days"] for c in closed) / len(closed) if closed else None}}
static/index.html CHANGED
@@ -97,6 +97,16 @@ table.proj th{text-align:right;font-weight:600;color:var(--muted);font-size:12px
97
  table.proj th:first-child,table.proj td:first-child{text-align:left}
98
  table.proj td{text-align:right;padding:8px 6px;border-bottom:1px solid var(--grid);font-variant-numeric:tabular-nums}
99
  table.proj td.big{font-weight:700;font-size:15px}
 
 
 
 
 
 
 
 
 
 
100
  .callout{border-left:3px solid var(--plan);background:var(--chip);border-radius:0 12px 12px 0;padding:12px 14px;font-size:13px;color:var(--ink-2);margin-top:14px}
101
  details{margin-top:10px}details summary{cursor:pointer;font-size:13px;color:var(--ink-2)}
102
  details table{width:100%;border-collapse:collapse;font-size:12px;margin-top:8px;font-variant-numeric:tabular-nums}
@@ -104,7 +114,8 @@ details td,details th{padding:4px 6px;border-bottom:1px solid var(--grid);text-a
104
  details td:first-child,details th:first-child{text-align:left}
105
  footer{color:var(--muted);font-size:12px;padding:0 0 36px}
106
  @media (max-width:900px){.kpis{grid-template-columns:1fr 1fr}.tile.hero{grid-column:1/-1}.steps{grid-template-columns:1fr 1fr}
107
- .grid2{grid-template-columns:1fr}.stat6{grid-template-columns:repeat(2,1fr)}}
 
108
  @media (max-width:560px){.hold .hide-s{display:none}.chartbox{height:280px}}
109
  </style>
110
  </head>
@@ -128,6 +139,7 @@ footer{color:var(--muted);font-size:12px;padding:0 0 36px}
128
  <nav class="wrap tabs" role="tablist" aria-label="Sections">
129
  <button role="tab" id="t-live" aria-selected="true" aria-controls="p-live">Live fund</button>
130
  <button role="tab" id="t-strategy" aria-selected="false" aria-controls="p-strategy">The strategy</button>
 
131
  </nav>
132
  </header>
133
 
@@ -175,6 +187,26 @@ footer{color:var(--muted);font-size:12px;padding:0 0 36px}
175
  </div>
176
  </section>
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  <!-- ===================================================== THE STRATEGY -->
179
  <section id="p-strategy" role="tabpanel" aria-labelledby="t-strategy" hidden>
180
  <div class="card">
@@ -280,17 +312,20 @@ $("themeBtn").onclick = () => {
280
  matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => redrawAll());
281
 
282
  /* ---------- tabs */
 
 
 
 
283
  function showTab(name) {
284
- for (const t of ["live", "strategy"]) {
285
  $("t-" + t).setAttribute("aria-selected", String(t === name)); $("p-" + t).hidden = t !== name;
286
  }
287
- setText($("lede"), name === "strategy"
288
- ? "An Alpaca live paper trade simulation, run by rules, not opinions. Below: how it picks its stocks, 27 years of backtest, and what a lump sum or a monthly SIP could grow to."
289
- : "An Alpaca live paper trade simulation, run by rules, not opinions. Below: what it is worth right now, how it compares with the S&P 500, and what it holds.");
290
  if (name === "strategy") loadStrategy();
291
- try { history.replaceState(null, "", name === "strategy" ? "#strategy" : "#"); } catch (e) {}
 
292
  }
293
- $("t-live").onclick = () => showTab("live"); $("t-strategy").onclick = () => showTab("strategy");
294
 
295
  /* ---------- chart plumbing */
296
  const charts = {};
@@ -414,7 +449,7 @@ function showToday() { // against the last close on the chart: Alpaca's
414
  signCls($("k-today"), pc);
415
  }
416
  async function loadPerformance() {
417
- try { perf = await get("/api/performance"); syncLive(); showPerf(); showToday(); }
418
  catch (e) { setText($("live-note"), "Performance unavailable right now: " + e.message); }
419
  }
420
  async function loadPortfolio() {
@@ -496,12 +531,90 @@ function showShortlist() {
496
  }
497
  async function loadStatus() {
498
  try {
499
- const s = await get("/api/status");
500
  setText($("k-next"), s.next_rebalance ? new Date(s.next_rebalance + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : "—");
501
  setText($("k-next-s"), s.done_this_month ? "this month's rebalance is done" : (s.market_open ? "market open" : "first trading day of the month"));
502
  } catch (e) {}
503
  }
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  /* ---------- THE STRATEGY */
506
  let strat = null, scen = "planning";
507
  async function loadStrategy() {
@@ -612,7 +725,7 @@ function redrawAll() { drawLive(true); if (strat) drawStrategy(); }
612
  /* ---------- start */
613
  loadPortfolio(); loadPerformance(); loadStatus(); loadRanking();
614
  setInterval(loadPortfolio, 30000); setInterval(loadStatus, 60000); setInterval(loadRanking, 600000); setInterval(loadPerformance, 60000);
615
- if (location.hash === "#strategy") showTab("strategy");
616
  </script>
617
  </body>
618
  </html>
 
97
  table.proj th:first-child,table.proj td:first-child{text-align:left}
98
  table.proj td{text-align:right;padding:8px 6px;border-bottom:1px solid var(--grid);font-variant-numeric:tabular-nums}
99
  table.proj td.big{font-weight:700;font-size:15px}
100
+ .stat4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
101
+ .ev{display:grid;grid-template-columns:150px 1fr;gap:16px;padding:16px 0;border-top:1px solid var(--grid)}
102
+ .ev:first-child{border-top:0;padding-top:6px}
103
+ .ev-date b{display:block;font-family:var(--brandfont);font-size:16px}
104
+ .ev-date span{font-size:12px;color:var(--muted)}
105
+ .ev-date .now{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--updraft);margin-right:6px;vertical-align:middle}
106
+ .ev-perf{font-size:13px;color:var(--ink-2)}
107
+ .ev-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:8px;font-size:13px}
108
+ .ev-k{width:58px;font-size:12px;color:var(--muted);font-weight:600}
109
+ .ev-small{font-size:12px;color:var(--muted);margin-top:8px}
110
  .callout{border-left:3px solid var(--plan);background:var(--chip);border-radius:0 12px 12px 0;padding:12px 14px;font-size:13px;color:var(--ink-2);margin-top:14px}
111
  details{margin-top:10px}details summary{cursor:pointer;font-size:13px;color:var(--ink-2)}
112
  details table{width:100%;border-collapse:collapse;font-size:12px;margin-top:8px;font-variant-numeric:tabular-nums}
 
114
  details td:first-child,details th:first-child{text-align:left}
115
  footer{color:var(--muted);font-size:12px;padding:0 0 36px}
116
  @media (max-width:900px){.kpis{grid-template-columns:1fr 1fr}.tile.hero{grid-column:1/-1}.steps{grid-template-columns:1fr 1fr}
117
+ .grid2{grid-template-columns:1fr}.stat6{grid-template-columns:repeat(2,1fr)}.stat4{grid-template-columns:repeat(2,1fr)}
118
+ .ev{grid-template-columns:1fr;gap:6px}}
119
  @media (max-width:560px){.hold .hide-s{display:none}.chartbox{height:280px}}
120
  </style>
121
  </head>
 
139
  <nav class="wrap tabs" role="tablist" aria-label="Sections">
140
  <button role="tab" id="t-live" aria-selected="true" aria-controls="p-live">Live fund</button>
141
  <button role="tab" id="t-strategy" aria-selected="false" aria-controls="p-strategy">The strategy</button>
142
+ <button role="tab" id="t-history" aria-selected="false" aria-controls="p-history">History</button>
143
  </nav>
144
  </header>
145
 
 
187
  </div>
188
  </section>
189
 
190
+ <!-- ===================================================== HISTORY -->
191
+ <section id="p-history" role="tabpanel" aria-labelledby="t-history" hidden>
192
+ <div class="stat4" id="h-stats"></div>
193
+ <div class="card">
194
+ <h2>Rebalance by rebalance</h2>
195
+ <p class="sub">Read from Alpaca's own orders, newest first. A holding is sold only once it drops out of the top 6; its slot
196
+ goes to the highest-ranked stock not held, and the stocks that stay are re-split to a third each.</p>
197
+ <div id="h-events" style="margin-top:10px"><p class="empty">Loading…</p></div>
198
+ </div>
199
+ <div class="card">
200
+ <h2>Every position</h2>
201
+ <p class="sub">Result = money taken out (sales, plus today's value while still held) minus money put in, so the monthly
202
+ top-ups and trims are counted.</p>
203
+ <div style="overflow-x:auto"><table class="hold" id="h-positions"><thead><tr>
204
+ <th>Stock</th><th class="hide-s">Bought</th><th>Sold</th><th class="r hide-s">Held for</th><th class="r hide-s">Put in</th><th class="r">Result</th><th class="r">Return</th>
205
+ </tr></thead><tbody><tr><td colspan="7" class="empty">Loading…</td></tr></tbody></table></div>
206
+ <p class="note" id="h-note"></p>
207
+ </div>
208
+ </section>
209
+
210
  <!-- ===================================================== THE STRATEGY -->
211
  <section id="p-strategy" role="tabpanel" aria-labelledby="t-strategy" hidden>
212
  <div class="card">
 
312
  matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => redrawAll());
313
 
314
  /* ---------- tabs */
315
+ const LEDE = {
316
+ live: "what it is worth right now, how it compares with the S&P 500, and what it holds.",
317
+ strategy: "how it picks its stocks, 27 years of backtest, and what a lump sum or a monthly SIP could grow to.",
318
+ history: "every monthly rebalance — what was bought, sold and kept — and how each position has done." };
319
  function showTab(name) {
320
+ for (const t of ["live", "strategy", "history"]) {
321
  $("t-" + t).setAttribute("aria-selected", String(t === name)); $("p-" + t).hidden = t !== name;
322
  }
323
+ setText($("lede"), "An Alpaca live paper trade simulation, run by rules, not opinions. Below: " + LEDE[name]);
 
 
324
  if (name === "strategy") loadStrategy();
325
+ if (name === "history") loadHistory();
326
+ try { history.replaceState(null, "", name === "live" ? "#" : "#" + name); } catch (e) {}
327
  }
328
+ for (const t of ["live", "strategy", "history"]) $("t-" + t).onclick = () => showTab(t);
329
 
330
  /* ---------- chart plumbing */
331
  const charts = {};
 
449
  signCls($("k-today"), pc);
450
  }
451
  async function loadPerformance() {
452
+ try { perf = await get("/api/performance"); syncLive(); showPerf(); showToday(); if (hist) renderHistory(); }
453
  catch (e) { setText($("live-note"), "Performance unavailable right now: " + e.message); }
454
  }
455
  async function loadPortfolio() {
 
531
  }
532
  async function loadStatus() {
533
  try {
534
+ const s = await get("/api/status"); stat = s;
535
  setText($("k-next"), s.next_rebalance ? new Date(s.next_rebalance + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : "—");
536
  setText($("k-next-s"), s.done_this_month ? "this month's rebalance is done" : (s.market_open ? "market open" : "first trading day of the month"));
537
  } catch (e) {}
538
  }
539
 
540
+ /* ---------- HISTORY */
541
+ let hist = null, stat = null, histAt = 0;
542
+ const fmtDay = d => new Date(d + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
543
+ const fmtHeld = d => d == null ? "—" : d < 60 ? `${d} day${d === 1 ? "" : "s"}` : `${(d / 30.44).toFixed(1)} months`;
544
+ const usdSigned = x => x == null ? "—" : (x >= 0 ? "+" : "−") + usd(Math.abs(x));
545
+ function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
546
+ function tile(label, value, sub, cls) {
547
+ const t = el("div", "tile"); t.append(el("div", "l", label)); const v = el("div", "v", value); if (cls) v.classList.add(cls);
548
+ t.append(v, el("div", "s", sub)); return t;
549
+ }
550
+ function periodRet(d0, d1) { // fund and S&P from the last close before d0 to the last close before d1 (or now)
551
+ if (!perf || !perf.dates || perf.dates.length < 2) return null;
552
+ const D = perf.dates; let a = -1, b = D.length - 1;
553
+ for (let i = 0; i < D.length; i++) { if (D[i] < d0) a = i; if (d1 && D[i] < d1) b = i; }
554
+ a = Math.max(a, 0); if (b <= a) return null;
555
+ return [perf.strategy[b] / perf.strategy[a] - 1, perf.spy[a] && perf.spy[b] ? perf.spy[b] / perf.spy[a] - 1 : null];
556
+ }
557
+ async function loadHistory() {
558
+ if (hist && Date.now() - histAt < 120000) return;
559
+ try { hist = await get("/api/history"); histAt = Date.now(); renderHistory(); }
560
+ catch (e) { $("h-events").textContent = ""; $("h-events").append(el("p", "empty", "History unavailable right now: " + e.message)); }
561
+ }
562
+ function renderHistory() {
563
+ const h = hist, S = h.summary, nameOf = r => [r.name, r.symbol].filter(Boolean)[0];
564
+ const next = stat && stat.next_rebalance ? new Date(stat.next_rebalance + "T12:00:00").toLocaleDateString([], { day: "numeric", month: "short" }) : "the next rebalance";
565
+ const st = $("h-stats"); st.textContent = "";
566
+ st.append(
567
+ tile("Rebalances", String(S.rebalances), S.first ? "since " + fmtDay(S.first) : "none yet"),
568
+ tile("Stocks replaced", S.swaps_per_rebalance == null ? "—" : S.swaps_per_rebalance.toFixed(1) + " of 3",
569
+ S.swaps_per_rebalance == null ? `none yet — the first possible change is ${next}` : "per rebalance, on average"),
570
+ tile("Sold at a profit", S.win_rate == null ? "—" : pct(S.win_rate, 0).replace("+", ""),
571
+ S.win_rate == null ? "no position has been sold yet" : `${S.closed} sold · average ${pct(S.avg_return)}`),
572
+ tile("Average holding", S.avg_days == null ? "—" : fmtHeld(Math.round(S.avg_days)),
573
+ S.best ? `best ${S.best.symbol} ${pct(S.best.return, 0)} · worst ${S.worst.symbol} ${pct(S.worst.return, 0)}` : "of the positions sold so far"));
574
+ const box = $("h-events"); box.textContent = "";
575
+ if (!h.events.length) box.append(el("p", "empty", "No rebalance yet — the first one buys the top 3."));
576
+ h.events.forEach((e, i) => {
577
+ const ev = el("div", "ev"), left = el("div", "ev-date"), body = el("div", "ev-body");
578
+ const b = el("b"); if (i === 0) b.append(el("i", "now")); b.append(document.createTextNode(fmtDay(e.date)));
579
+ left.append(b, el("span", null, e.first ? "Fund started" : i === 0 ? "Current portfolio" : "Monthly rebalance"));
580
+ const r = periodRet(e.date, i > 0 ? h.events[i - 1].date : null);
581
+ if (r) {
582
+ const pp = el("div", "ev-perf"); pp.append(document.createTextNode((i === 0 ? "Held since: " : "While held: ") + "Updraft "));
583
+ const u = el("b", null, pct(r[0])); signCls(u, r[0]); pp.append(u, document.createTextNode(" · S&P 500 " + pct(r[1]) + (i === 0 ? " so far" : "")));
584
+ body.append(pp);
585
+ }
586
+ const row = (k, items) => { if (!items.length) return; const rw = el("div", "ev-row"); rw.append(el("span", "ev-k", k), ...items); body.append(rw); };
587
+ const chip = (sym, cls, title) => { const c = el("span", "tag " + cls, sym); if (title) c.title = title; return c; };
588
+ const names = {}; for (const p of h.open.concat(h.closed)) names[p.symbol] = p.name;
589
+ row("Bought", e.bought.map(x => chip(x, "buy", names[x])));
590
+ row("Sold", e.sold.flatMap(x => { const g = el("span", null, pct(x.return)); signCls(g, x.return);
591
+ return [chip(x.symbol, "sell", x.name), g, el("span", "muted", `after ${fmtHeld(x.days)} · ${usdSigned(x.pnl)}`)]; }));
592
+ row("Kept", e.kept.map(x => chip(x, "held", names[x])));
593
+ const notes = [];
594
+ if (e.sold.length) notes.push(`${e.sold.map(x => x.symbol).join(", ")} dropped out of the top 6`);
595
+ if (e.resplit.length) notes.push("re-split: " + e.resplit.map(x => `${x.value > 0 ? "topped up" : "trimmed"} ${x.symbol} ${usd(Math.abs(x.value))}`).join(", "));
596
+ if (e.added) notes.push(`${usd(e.added)} added since the previous rebalance`);
597
+ notes.push(`${usd(e.traded)} traded`);
598
+ body.append(el("div", "ev-small", notes.join(" · ")));
599
+ ev.append(left, body); box.append(ev);
600
+ });
601
+ const tb = $("h-positions").querySelector("tbody"); tb.textContent = "";
602
+ const rows = h.open.map(x => ({ ...x, held: true })).concat(h.closed);
603
+ if (!rows.length) { const tr = tb.insertRow(); const td = tr.insertCell(); td.colSpan = 7; td.className = "empty"; td.textContent = "No positions yet."; }
604
+ for (const x of rows) {
605
+ const tr = tb.insertRow(); if (x.held) tr.className = "is-held";
606
+ const a = tr.insertCell(); a.append(el("div", "tick", x.symbol), el("div", "co", x.name || ""));
607
+ const bd = tr.insertCell(); bd.className = "hide-s"; bd.textContent = fmtDay(x.entered);
608
+ const sc = tr.insertCell(); if (x.held) sc.append(el("span", "tag held", "Still held")); else sc.textContent = fmtDay(x.exited);
609
+ const hd = tr.insertCell(); hd.className = "r hide-s"; hd.textContent = fmtHeld(x.days);
610
+ const pi = tr.insertCell(); pi.className = "r hide-s"; pi.textContent = usd(x.put_in);
611
+ const pl = tr.insertCell(); pl.className = "r"; pl.textContent = usdSigned(x.pnl); signCls(pl, x.pnl);
612
+ const rt = tr.insertCell(); rt.className = "r"; rt.textContent = pct(x.return); signCls(rt, x.return);
613
+ }
614
+ setText($("h-note"), (h.pending_deposits > 0 ? `${usd(h.pending_deposits)} added since the last rebalance — it is invested at the next one. ` : "") +
615
+ "Positions still held are valued at today's price. Updates every few minutes.");
616
+ }
617
+
618
  /* ---------- THE STRATEGY */
619
  let strat = null, scen = "planning";
620
  async function loadStrategy() {
 
725
  /* ---------- start */
726
  loadPortfolio(); loadPerformance(); loadStatus(); loadRanking();
727
  setInterval(loadPortfolio, 30000); setInterval(loadStatus, 60000); setInterval(loadRanking, 600000); setInterval(loadPerformance, 60000);
728
+ if (location.hash === "#strategy" || location.hash === "#history") showTab(location.hash.slice(1));
729
  </script>
730
  </body>
731
  </html>
tests/test_qt3_space.py CHANGED
@@ -303,3 +303,28 @@ def test_ranking_endpoint_while_first_build_runs(monkeypatch, tmp_path):
303
  import app as space
304
  r = TestClient(space.app).get("/api/ranking")
305
  assert r.status_code == 200 and r.json()["age_hours"] is None and "ranked" not in r.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  import app as space
304
  r = TestClient(space.app).get("/api/ranking")
305
  assert r.status_code == 200 and r.json()["age_hours"] is None and "ranked" not in r.json()
306
+
307
+
308
+ def test_history_replays_rebalances_from_orders():
309
+ from qt3 import history
310
+
311
+ def o(day, sym, side, qty, px, at="T14:00:00Z"):
312
+ return {"client_order_id": f"qt3-{day.replace('-', '')}-{sym}-{side}", "symbol": sym, "side": side,
313
+ "filled_qty": str(qty), "filled_avg_price": str(px), "filled_at": day + at}
314
+ orders = [o("2026-10-12", s, "buy", 1, 100) for s in "ABC"] + [
315
+ o("2026-11-02", "C", "sell", 1, 120, "T14:00:00Z"), o("2026-11-02", "D", "buy", 1, 110, "T14:05:00Z"),
316
+ o("2026-11-02", "A", "buy", 0.05, 100, "T14:05:00Z"), o("2026-11-02", "B", "sell", 0.03, 100, "T14:00:00Z"),
317
+ {"client_order_id": "manual-1", "symbol": "Z", "side": "buy", "filled_qty": "5", "filled_avg_price": "10"}]
318
+ pos = {"A": {"market_value": 120.0}, "B": {"market_value": 90.0}, "D": {"market_value": 100.0}}
319
+ h = history.build(orders, pos, {"2026-10-01": 10000.0, "2026-10-20": 1000.0}, {"C": "Cee Corp"})
320
+ new, first = h["events"]
321
+ assert first["first"] and first["bought"] == ["A", "B", "C"] and first["added"] == 0
322
+ assert new["bought"] == ["D"] and new["kept"] == ["A", "B"] and new["added"] == 1000.0
323
+ assert [s["symbol"] for s in new["sold"]] == ["C"] and new["sold"][0]["return"] == pytest.approx(0.2)
324
+ assert new["sold"][0]["days"] == 21 and new["sold"][0]["name"] == "Cee Corp"
325
+ assert {r["symbol"]: r["value"] for r in new["resplit"]} == {"A": 5.0, "B": -3.0}
326
+ op = {r["symbol"]: r for r in h["open"]}
327
+ assert set(op) == {"A", "B", "D"} # the manual order is ignored
328
+ assert op["A"]["return"] == pytest.approx(120 / 105 - 1) and op["B"]["return"] == pytest.approx(93 / 100 - 1)
329
+ s = h["summary"]
330
+ assert s["rebalances"] == 2 and s["swaps_per_rebalance"] == 1 and s["closed"] == 1 and s["win_rate"] == 1