while25 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.
Files changed (50) hide show
  1. while25/__init__.py +341 -0
  2. while25/_costs/brokers/alpaca.json +96 -0
  3. while25/_costs/brokers/binance.json +34 -0
  4. while25/_costs/brokers/coinbase.json +34 -0
  5. while25/_costs/brokers/ibkr.json +39 -0
  6. while25/_costs/brokers/upstox.json +175 -0
  7. while25/_costs/brokers/zerodha.json +175 -0
  8. while25/_costs/crypto_alpaca.json +27 -0
  9. while25/_costs/global_crypto.json +18 -0
  10. while25/_costs/in_nse_equity.json +238 -0
  11. while25/_costs/in_nse_etf.json +352 -0
  12. while25/_costs/in_nse_fo.json +450 -0
  13. while25/_costs/us_crypto.json +18 -0
  14. while25/_costs/us_equity.json +175 -0
  15. while25/_costs/us_options.json +172 -0
  16. while25/_days.py +123 -0
  17. while25/_figures.py +233 -0
  18. while25/_runtime.py +49 -0
  19. while25/_universes/banknifty.json +80 -0
  20. while25/_universes/ndx100.json +520 -0
  21. while25/_universes/nifty50.json +260 -0
  22. while25/_universes/nifty500.json +2505 -0
  23. while25/_universes/sp500.json +2525 -0
  24. while25/assume.py +263 -0
  25. while25/backtest.py +881 -0
  26. while25/barline.py +160 -0
  27. while25/combo_legs.py +238 -0
  28. while25/errors.py +77 -0
  29. while25/fonts/IBMPlexMono-Regular.ttf +0 -0
  30. while25/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  31. while25/fonts/Inter-Bold.ttf +0 -0
  32. while25/fonts/Inter-Regular.ttf +0 -0
  33. while25/fonts/Inter-SemiBold.ttf +0 -0
  34. while25/fonts/OFL-IBMPlexMono.txt +93 -0
  35. while25/fonts/OFL-Inter.txt +93 -0
  36. while25/future_pick.py +77 -0
  37. while25/inputs.py +215 -0
  38. while25/instruments.py +488 -0
  39. while25/modules.py +397 -0
  40. while25/money.py +24 -0
  41. while25/option_pick.py +221 -0
  42. while25/plots.py +147 -0
  43. while25/report.py +644 -0
  44. while25/ui.py +680 -0
  45. while25/universes.py +70 -0
  46. while25-0.1.0.dist-info/METADATA +3194 -0
  47. while25-0.1.0.dist-info/RECORD +50 -0
  48. while25-0.1.0.dist-info/WHEEL +5 -0
  49. while25-0.1.0.dist-info/licenses/LICENSE +201 -0
  50. while25-0.1.0.dist-info/top_level.txt +1 -0
while25/report.py ADDED
@@ -0,0 +1,644 @@
1
+ """House-style financial PDF reports.
2
+
3
+ from while25 import report
4
+
5
+ r = report.Report("Qualcomm (QCOM)", subtitle="Equity report",
6
+ source="Yahoo Finance", as_of="2026-09-27", currency="USD")
7
+ r.summary("Qualcomm trades at **17.4x** earnings, below its five-year average.")
8
+ r.metrics({"Price": 165.2, "Market cap": 1.8e11, "1Y return": -0.084},
9
+ kinds={"Price": "money", "Market cap": "money", "1Y return": "pct"})
10
+ r.section("Price")
11
+ r.price_chart(prices) # a DataFrame with Close (and Volume)
12
+ r.section("Financials")
13
+ r.table(income, kinds={"Revenue": "money", "Net margin": "pct"}, title="Income statement")
14
+ r.chart(monthly_returns, kind="bar", title="Monthly return", y="pct")
15
+ path = r.save() # reports/qualcomm-qcom_2026-09-27.pdf
16
+
17
+ Every page carries the title, the as-of date and "Page X of Y"; the last page
18
+ names the source and says the report is not investment advice. A value the
19
+ source did not provide prints as "—", never as 0.
20
+
21
+ Needs reportlab, matplotlib and pandas (bundled in the terminal; elsewhere
22
+ `pip install "while25[report]"`). They are imported when a report is SAVED, so
23
+ `import while25` stays dependency-free.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import io
28
+ import math
29
+ import re
30
+ from datetime import date, datetime
31
+ from pathlib import Path
32
+ from typing import Any
33
+ from xml.sax.saxutils import escape
34
+
35
+ __all__ = ["Report", "fmt"]
36
+
37
+ FONTS = Path(__file__).with_name("fonts")
38
+
39
+ # The terminal's light theme — a report is printed, so it uses the paper palette.
40
+ INK, DIM, RULE, FILL, LINE = "#1A1714", "#6B6560", "#E0DCD6", "#F5F2EE", "#C8C2BA"
41
+ AMBER, GAIN, LOSS = "#B8860B", "#16A34A", "#DC2626"
42
+ SERIES = [AMBER, "#2F3B4C", "#6B8E9E", "#A06A4B", "#7C7F3A"]
43
+
44
+ MINUS = "−" # a true minus sign: "−8.4%", not "-8.4%"
45
+ DASH = "—" # the source did not provide it
46
+
47
+ _SYMBOLS = {"USD": "$", "INR": "₹", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
48
+ "HKD": "HK$", "SGD": "S$", "AUD": "A$", "CAD": "C$"}
49
+ _KINDS = ("auto", "num", "int", "money", "pct", "x", "compact", "text")
50
+ # A reportlab Table sets Helvetica on every cell unless told otherwise — even
51
+ # cells that are styled paragraphs — so it would be embedded in every report.
52
+ _TABLE_FONT = ("FONTNAME", (0, 0), (-1, -1), "Inter-Regular")
53
+
54
+
55
+ # ── numbers ───────────────────────────────────────────────────────────────
56
+
57
+ def _absent(v: Any) -> bool:
58
+ if v is None or (isinstance(v, str) and v.strip() == ""):
59
+ return True
60
+ if isinstance(v, float) and not math.isfinite(v):
61
+ return True
62
+ try: # pandas NA / NaT without importing pandas
63
+ return bool(v != v)
64
+ except (TypeError, ValueError):
65
+ return False
66
+
67
+
68
+ def _compact(v: float, decimals: int) -> str | None:
69
+ for size, suffix in ((1e12, "T"), (1e9, "B"), (1e6, "M")):
70
+ if abs(v) >= size:
71
+ return f"{abs(v) / size:,.{decimals}f}{suffix}"
72
+ return None
73
+
74
+
75
+ def _day_month_year(d: Any) -> str:
76
+ """A date the way a desk writes it: "2 Oct 2026". The day comes from the
77
+ date itself: strftime's "%-d" (day without a leading zero) is a Mac and
78
+ Linux extension that Windows rejects, which crashed every report there."""
79
+ return f"{d.day} {d.strftime('%b %Y')}"
80
+
81
+
82
+ def fmt(value: Any, kind: str = "auto", currency: str | None = None,
83
+ decimals: int | None = None) -> str:
84
+ """One value the way a desk writes it.
85
+
86
+ kind: "money" (currency symbol; 1.8e11 -> $180.0B), "pct" (a FRACTION:
87
+ -0.084 -> −8.4%), "x" (a multiple: 17.4x), "int", "num" (2 dp), "compact"
88
+ (4.2B), "text", or "auto" (by type). Absent -> "—", negatives -> "−".
89
+ """
90
+ if kind not in _KINDS:
91
+ raise ValueError(f"kind must be one of {', '.join(_KINDS)}; got {kind!r}")
92
+ if _absent(value):
93
+ return DASH
94
+ if kind == "text" or isinstance(value, str):
95
+ return str(value)
96
+ if isinstance(value, bool):
97
+ return "Yes" if value else "No"
98
+ if isinstance(value, (datetime, date)) or hasattr(value, "to_pydatetime"):
99
+ return _day_month_year(value)
100
+ try:
101
+ v = float(value)
102
+ except (TypeError, ValueError):
103
+ return str(value)
104
+ if kind == "auto":
105
+ kind = "int" if float(v).is_integer() and not isinstance(value, float) else "num"
106
+ sign = MINUS if v < 0 else ""
107
+ a = abs(v)
108
+ if kind == "pct":
109
+ return f"{sign}{a * 100:,.{1 if decimals is None else decimals}f}%"
110
+ if kind == "x":
111
+ return f"{sign}{a:,.{1 if decimals is None else decimals}f}x"
112
+ if kind == "int":
113
+ return f"{sign}{a:,.0f}"
114
+ if kind == "compact":
115
+ whole = 0 if float(a).is_integer() else 2
116
+ return sign + (_compact(a, 1 if decimals is None else decimals)
117
+ or f"{a:,.{whole if decimals is None else decimals}f}")
118
+ if kind == "money":
119
+ code = (currency or "").upper()
120
+ symbol = _SYMBOLS.get(code, f"{code} " if code else "")
121
+ body = _compact(a, 1 if decimals is None else decimals) or f"{a:,.{2 if decimals is None else decimals}f}"
122
+ return f"{sign}{symbol}{body}"
123
+ # num
124
+ if decimals is None and 0 < a < 0.01:
125
+ return f"{sign}{a:.3g}" if a >= 1e-4 else f"{sign}{a:.3g}"
126
+ return f"{sign}{a:,.{2 if decimals is None else decimals}f}"
127
+
128
+
129
+ def _as_date(v: Any) -> str:
130
+ if v is None:
131
+ return _day_month_year(date.today())
132
+ if isinstance(v, str):
133
+ try:
134
+ return _day_month_year(datetime.fromisoformat(v))
135
+ except ValueError:
136
+ return v
137
+ return fmt(v)
138
+
139
+
140
+ def _slug(s: str) -> str:
141
+ return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-") or "report"
142
+
143
+
144
+ def _stated_volume(pd, df, col):
145
+ """The bars that state a volume, as numbers; None when none does. An
146
+ absent volume (None, NaN, unreadable) is not drawn, never drawn as 0."""
147
+ s = pd.to_numeric(df[col], errors="coerce").dropna()
148
+ return s if len(s) else None
149
+
150
+
151
+ def _dated(pd, data: Any):
152
+ """Any price shape, indexed by real dates: a DatetimeIndex, a `date` column,
153
+ or while25.data rows whose `time` is epoch MILLISECONDS. Read as the default
154
+ nanoseconds, those chart as 1970."""
155
+ df = (data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)).copy()
156
+ cols = {str(c).lower(): c for c in df.columns}
157
+ # The instant first: a history_span bar carries both, and its trading
158
+ # `date` would stack a day's intraday bars on one point.
159
+ if "time" in cols and pd.api.types.is_numeric_dtype(df[cols["time"]]):
160
+ df = df.set_index(cols["time"])
161
+ df.index = pd.to_datetime(df.index, unit="ms")
162
+ elif "date" in cols:
163
+ df = df.set_index(cols["date"])
164
+ df.index = pd.to_datetime(df.index)
165
+ elif not isinstance(df.index, pd.DatetimeIndex):
166
+ df.index = pd.to_datetime(df.index)
167
+ return df
168
+
169
+
170
+ def _markup(text: str) -> str:
171
+ """Escape everything, then honour **bold** — text is data, never markup."""
172
+ return re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", escape(str(text)))
173
+
174
+
175
+ # ── the report ────────────────────────────────────────────────────────────
176
+
177
+ class Report:
178
+ """A report built block by block, rendered on save()."""
179
+
180
+ def __init__(self, title: str, subtitle: str | None = None, *, source: str | None = None,
181
+ as_of: Any = None, currency: str | None = None, pagesize: str = "A4") -> None:
182
+ self.title, self.subtitle, self.source = title, subtitle, source
183
+ self.as_of = _as_date(as_of)
184
+ self._as_of_raw = as_of
185
+ self.currency = currency
186
+ self.pagesize = pagesize
187
+ self._blocks: list[tuple[str, dict]] = []
188
+
189
+ # Everything below only records; rendering happens in save().
190
+ def summary(self, text: str) -> None:
191
+ """The lead: two or three sentences a reader could stop after."""
192
+ self._blocks.append(("summary", {"text": text}))
193
+
194
+ def section(self, title: str) -> None:
195
+ self._blocks.append(("section", {"title": title}))
196
+
197
+ def text(self, text: str) -> None:
198
+ self._blocks.append(("text", {"text": text}))
199
+
200
+ def bullets(self, items: list[str]) -> None:
201
+ self._blocks.append(("bullets", {"items": list(items)}))
202
+
203
+ def metrics(self, values: dict[str, Any], kinds: dict[str, str] | None = None) -> None:
204
+ """The key figures, as tiles. `kinds` maps a label to a fmt() kind."""
205
+ self._blocks.append(("metrics", {"values": dict(values), "kinds": kinds or {}}))
206
+
207
+ def table(self, data: Any, kinds: dict[str, str] | None = None, title: str | None = None,
208
+ max_rows: int | None = None) -> None:
209
+ """A DataFrame, or a list of dicts. A named/non-range index becomes the first column."""
210
+ self._blocks.append(("table", {"data": data, "kinds": kinds or {}, "title": title,
211
+ "max_rows": max_rows}))
212
+
213
+ def chart(self, data: Any, kind: str = "line", title: str | None = None,
214
+ y: str = "num", height_mm: float = 62) -> None:
215
+ """A Series (one line or bar set) or a DataFrame (one line per column)."""
216
+ if kind not in ("line", "bar", "area"):
217
+ raise ValueError("kind must be 'line', 'bar' or 'area'")
218
+ self._blocks.append(("chart", {"data": data, "kind": kind, "title": title, "y": y,
219
+ "height": height_mm}))
220
+
221
+ def price_chart(self, prices: Any, title: str | None = "Price", height_mm: float = 78) -> None:
222
+ """Close (line) over Volume (bars), from a DataFrame with a date index or `date` column."""
223
+ self._blocks.append(("price", {"data": prices, "title": title, "height": height_mm}))
224
+
225
+ def figure(self, fig: Any, title: str | None = None, height_mm: float | None = None) -> None:
226
+ """Place a matplotlib Figure you drew yourself."""
227
+ self._blocks.append(("figure", {"fig": fig, "title": title, "height": height_mm}))
228
+
229
+ def _stamp(self) -> str:
230
+ """The as-of date as YYYY-MM-DD for a file name; today when it is not a date."""
231
+ v = self._as_of_raw
232
+ if isinstance(v, (datetime, date)) or hasattr(v, "to_pydatetime"):
233
+ return v.strftime("%Y-%m-%d")
234
+ if isinstance(v, str):
235
+ try:
236
+ return datetime.fromisoformat(v).strftime("%Y-%m-%d")
237
+ except ValueError:
238
+ pass
239
+ return date.today().isoformat()
240
+
241
+ def save(self, path: str | Path | None = None) -> str:
242
+ """Render and write the PDF. Returns its absolute path."""
243
+ if path is None:
244
+ path = Path("reports") / f"{_slug(self.title)}_{self._stamp()}.pdf"
245
+ out = Path(path).resolve()
246
+ out.parent.mkdir(parents=True, exist_ok=True)
247
+ _Renderer(self).render(out)
248
+ return str(out)
249
+
250
+
251
+ # ── rendering (the only place the heavy libraries are imported) ───────────
252
+
253
+ def _need():
254
+ try:
255
+ import matplotlib
256
+ import pandas
257
+ import reportlab # noqa: F401
258
+ except ImportError as exc:
259
+ raise ImportError(
260
+ f"while25.report needs reportlab, matplotlib and pandas ({exc.name} is missing). "
261
+ "The terminal bundles them; elsewhere: pip install \"while25[report]\"") from exc
262
+ matplotlib.use("Agg")
263
+ return pandas
264
+
265
+
266
+ class _Renderer:
267
+ def __init__(self, rep: Report) -> None:
268
+ self.rep = rep
269
+
270
+ def render(self, out: Path) -> None:
271
+ self.pd = _need()
272
+ from reportlab.lib.pagesizes import A4, letter
273
+ from reportlab.lib.units import mm
274
+ from reportlab.platypus import SimpleDocTemplate
275
+
276
+ self._fonts()
277
+ self.mm = mm
278
+ size = letter if self.rep.pagesize.lower() == "letter" else A4
279
+ doc = SimpleDocTemplate(str(out), pagesize=size, leftMargin=18 * mm, rightMargin=18 * mm,
280
+ topMargin=22 * mm, bottomMargin=20 * mm,
281
+ title=self.rep.title, author="While25",
282
+ # Or every page opens in Helvetica: no ₹, and not ours.
283
+ initialFontName="Inter-Regular",
284
+ subject=self.rep.subtitle or "")
285
+ # The frame pads 6 pt each side; sizing to doc.width overflowed the margin.
286
+ self.width = doc.width - 12
287
+ story = self._cover()
288
+ for kind, args in self.rep._blocks:
289
+ story += getattr(self, f"_{kind}")(**args)
290
+ story += self._closing()
291
+ doc.build(story, canvasmaker=self._canvas(size))
292
+
293
+ # fonts and styles --------------------------------------------------------
294
+ def _fonts(self) -> None:
295
+ from matplotlib import font_manager
296
+ from reportlab.lib.styles import ParagraphStyle
297
+ from reportlab.pdfbase import pdfmetrics
298
+ from reportlab.pdfbase.ttfonts import TTFont
299
+
300
+ for name in ("Inter-Regular", "Inter-SemiBold", "Inter-Bold",
301
+ "IBMPlexMono-Regular", "IBMPlexMono-SemiBold"):
302
+ if name not in pdfmetrics.getRegisteredFontNames():
303
+ pdfmetrics.registerFont(TTFont(name, str(FONTS / f"{name}.ttf")))
304
+ font_manager.fontManager.addfont(str(FONTS / f"{name}.ttf"))
305
+ pdfmetrics.registerFontFamily("Inter", normal="Inter-Regular", bold="Inter-SemiBold",
306
+ italic="Inter-Regular", boldItalic="Inter-SemiBold")
307
+
308
+ def st(name, **kw):
309
+ # bulletFontName too: its default is Helvetica, embedded even with no bullet.
310
+ base = dict(fontName="Inter-Regular", bulletFontName="Inter-Regular", fontSize=9.5,
311
+ leading=14, textColor=INK)
312
+ base.update(kw)
313
+ return ParagraphStyle(name, **base)
314
+
315
+ self.s = {
316
+ "eyebrow": st("eyebrow", fontName="Inter-SemiBold", fontSize=7.5, leading=10,
317
+ textColor=AMBER),
318
+ "title": st("title", fontName="Inter-Bold", fontSize=22, leading=27, spaceBefore=3),
319
+ "meta": st("meta", fontSize=8.5, leading=12, textColor=DIM, spaceBefore=4),
320
+ "lead": st("lead", fontSize=11, leading=16.5, spaceBefore=12, spaceAfter=4),
321
+ "h": st("h", fontName="Inter-SemiBold", fontSize=12.5, leading=16, spaceBefore=16,
322
+ spaceAfter=6),
323
+ "caption": st("caption", fontName="Inter-SemiBold", fontSize=8.5, leading=11,
324
+ textColor=INK, spaceBefore=8, spaceAfter=4),
325
+ "body": st("body", spaceAfter=6),
326
+ "small": st("small", fontSize=7.5, leading=10.5, textColor=DIM, spaceAfter=4),
327
+ "figure": st("figure", fontName="IBMPlexMono-SemiBold", fontSize=14, leading=18),
328
+ "label": st("label", fontName="Inter-SemiBold", fontSize=6.8, leading=9,
329
+ textColor=DIM),
330
+ "th": st("th", fontName="Inter-SemiBold", fontSize=7.3, leading=9.5, textColor=DIM),
331
+ "td": st("td", fontSize=8.3, leading=11),
332
+ "tdn": st("tdn", fontName="IBMPlexMono-Regular", fontSize=8, leading=11,
333
+ alignment=2),
334
+ }
335
+
336
+ def _p(self, text: str, style: str, color: str | None = None, align: int | None = None):
337
+ from reportlab.lib.styles import ParagraphStyle
338
+ from reportlab.platypus import Paragraph
339
+ s = self.s[style]
340
+ if color or align is not None:
341
+ s = ParagraphStyle(f"{style}-x", parent=s, textColor=color or s.textColor,
342
+ alignment=s.alignment if align is None else align)
343
+ return Paragraph(text, s)
344
+
345
+ # page furniture ----------------------------------------------------------
346
+ def _canvas(self, size):
347
+ from reportlab.pdfgen import canvas as rl_canvas
348
+ rep, mm, width = self.rep, self.mm, size[0]
349
+
350
+ def furniture(c, total: int) -> None:
351
+ n = c.getPageNumber()
352
+ left, right = 18 * mm + 6, width - 18 * mm - 6
353
+ c.saveState()
354
+ if n > 1:
355
+ c.setFont("Inter-SemiBold", 7.5)
356
+ c.setFillColor(DIM)
357
+ c.drawString(left, size[1] - 13 * mm, rep.title)
358
+ c.drawRightString(right, size[1] - 13 * mm, f"As of {rep.as_of}")
359
+ c.setStrokeColor(RULE)
360
+ c.setLineWidth(0.6)
361
+ c.line(left, size[1] - 15 * mm, right, size[1] - 15 * mm)
362
+ c.setStrokeColor(RULE)
363
+ c.setLineWidth(0.6)
364
+ c.line(left, 13 * mm, right, 13 * mm)
365
+ c.setFont("Inter-Regular", 7)
366
+ c.setFillColor(DIM)
367
+ c.drawString(left, 9 * mm, "While25 · For information only. Not investment advice.")
368
+ c.drawRightString(right, 9 * mm, f"Page {n} of {total}")
369
+ c.restoreState()
370
+
371
+ class Numbered(rl_canvas.Canvas):
372
+ """Two passes, so every page can say how many there are."""
373
+
374
+ def __init__(self, *a, **k):
375
+ super().__init__(*a, **k)
376
+ self._pages: list[dict] = []
377
+
378
+ def showPage(self):
379
+ self._pages.append(dict(self.__dict__))
380
+ self._startPage()
381
+
382
+ def save(self):
383
+ total = len(self._pages)
384
+ for state in self._pages:
385
+ self.__dict__.update(state)
386
+ furniture(self, total)
387
+ super().showPage()
388
+ super().save()
389
+
390
+ return Numbered
391
+
392
+ def _cover(self) -> list:
393
+ from reportlab.platypus import HRFlowable
394
+ rep = self.rep
395
+ meta = [f"As of {rep.as_of}"]
396
+ if rep.source:
397
+ meta.append(f"Source: {escape(rep.source)}")
398
+ if rep.currency:
399
+ meta.append(f"Figures in {escape(rep.currency.upper())}")
400
+ return [
401
+ self._p(escape((rep.subtitle or "Report").upper()), "eyebrow"),
402
+ self._p(escape(rep.title), "title"),
403
+ self._p(" · ".join(meta), "meta"),
404
+ HRFlowable(width="100%", thickness=1.2, color=AMBER, spaceBefore=10, spaceAfter=2),
405
+ ]
406
+
407
+ def _closing(self) -> list:
408
+ rep = self.rep
409
+ src = f"Figures come from {escape(rep.source)}, as of {rep.as_of}. " if rep.source else \
410
+ f"Figures are as of {rep.as_of}. "
411
+ return self._section("Sources and notes") + [
412
+ self._p(src + "They may be delayed or later revised. "
413
+ f"{DASH} marks a value the source did not provide.", "small"),
414
+ self._p("This report is for information only and is not investment advice, "
415
+ "an offer, or a solicitation to buy or sell any security. Past "
416
+ "performance does not indicate future results.", "small"),
417
+ ]
418
+
419
+ # blocks ------------------------------------------------------------------
420
+ def _summary(self, text: str) -> list:
421
+ return [self._p(_markup(text), "lead")]
422
+
423
+ def _section(self, title: str) -> list:
424
+ p = self._p(escape(title), "h")
425
+ p.keepWithNext = True
426
+ return [p]
427
+
428
+ def _text(self, text: str) -> list:
429
+ return [self._p(_markup(text), "body")]
430
+
431
+ def _bullets(self, items: list[str]) -> list:
432
+ from reportlab.platypus import ListFlowable, ListItem
433
+ return [ListFlowable([ListItem(self._p(_markup(i), "body"), leftIndent=12)
434
+ for i in items],
435
+ bulletType="bullet", start="•", bulletFontName="Inter-Regular",
436
+ bulletFontSize=7, bulletColor=AMBER, leftIndent=12)]
437
+
438
+ def _metrics(self, values: dict, kinds: dict) -> list:
439
+ from reportlab.platypus import Table, TableStyle
440
+ cells = []
441
+ for label, v in values.items():
442
+ text = fmt(v, kinds.get(label, "auto"), currency=self.rep.currency)
443
+ color = LOSS if isinstance(v, (int, float)) and not _absent(v) and v < 0 else INK
444
+ cells.append([self._p(escape(label.upper()), "label"),
445
+ self._p(escape(text), "figure", color=color)])
446
+ if not cells:
447
+ return []
448
+ per_row = 4 if len(cells) != 3 else 3
449
+ rows = [cells[i:i + per_row] for i in range(0, len(cells), per_row)]
450
+ rows[-1] += [["", ""]] * (per_row - len(rows[-1]))
451
+ tile = [_TABLE_FONT, ("LEFTPADDING", (0, 0), (-1, -1), 0),
452
+ ("RIGHTPADDING", (0, 0), (-1, -1), 0), ("TOPPADDING", (0, 0), (-1, -1), 1),
453
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 1)]
454
+ grid = [[Table([[c[0]], [c[1]]], colWidths=[self.width / per_row - 20], style=tile)
455
+ if c[0] else ""
456
+ for c in row] for row in rows]
457
+ t = Table(grid, colWidths=[self.width / per_row] * per_row, hAlign="LEFT")
458
+ t.setStyle(TableStyle([
459
+ _TABLE_FONT,
460
+ ("BACKGROUND", (0, 0), (-1, -1), FILL),
461
+ ("LINEAFTER", (0, 0), (-2, -1), 3, "#FFFFFF"),
462
+ ("LINEBELOW", (0, 0), (-1, -2), 3, "#FFFFFF"),
463
+ ("TOPPADDING", (0, 0), (-1, -1), 8), ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
464
+ ("LEFTPADDING", (0, 0), (-1, -1), 10), ("RIGHTPADDING", (0, 0), (-1, -1), 10),
465
+ ]))
466
+ from reportlab.platypus import Spacer
467
+ return [Spacer(1, 8), t, Spacer(1, 4)]
468
+
469
+ def _frame(self, data):
470
+ pd = self.pd
471
+ df = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)
472
+ if not isinstance(df.index, pd.RangeIndex):
473
+ df = df.reset_index()
474
+ if df.columns[0] in ("index", None):
475
+ df = df.rename(columns={df.columns[0]: ""})
476
+ return df
477
+
478
+ def _table(self, data: Any, kinds: dict, title: str | None, max_rows: int | None) -> list:
479
+ from reportlab.platypus import Table, TableStyle
480
+ pd = self.pd
481
+ head = [self._p(escape(title), "caption")] if title else []
482
+ df = self._frame(data)
483
+ if df.empty or len(df.columns) == 0:
484
+ return head + [self._p("No data.", "small")]
485
+ note = []
486
+ if max_rows is not None and len(df) > max_rows:
487
+ note = [self._p(f"Showing the first {max_rows} of {len(df):,} rows.", "small")]
488
+ df = df.head(max_rows)
489
+ numeric = {c: pd.api.types.is_numeric_dtype(df[c]) and not pd.api.types.is_bool_dtype(df[c])
490
+ for c in df.columns}
491
+ rows = [[self._p(escape(str(c).upper()), "th", align=2 if numeric[c] else 0)
492
+ for c in df.columns]]
493
+ for _, r in df.iterrows():
494
+ row = []
495
+ for c in df.columns:
496
+ v = r[c]
497
+ text = fmt(v, kinds.get(str(c), "auto"), currency=self.rep.currency)
498
+ if numeric[c]:
499
+ neg = not _absent(v) and float(v) < 0
500
+ row.append(self._p(escape(text), "tdn", color=LOSS if neg else None))
501
+ else:
502
+ row.append(self._p(escape(text), "td"))
503
+ rows.append(row)
504
+ widths = self._widths(df, numeric, [[p.text for p in r] for r in rows])
505
+ t = Table(rows, colWidths=widths, repeatRows=1, hAlign="LEFT")
506
+ style = [
507
+ _TABLE_FONT,
508
+ ("LINEBELOW", (0, 0), (-1, 0), 0.8, LINE),
509
+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
510
+ ("TOPPADDING", (0, 0), (-1, -1), 3.2), ("BOTTOMPADDING", (0, 0), (-1, -1), 3.2),
511
+ ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5),
512
+ ("LINEBELOW", (0, -1), (-1, -1), 0.6, RULE),
513
+ ]
514
+ style += [("BACKGROUND", (0, i), (-1, i), FILL) for i in range(2, len(rows), 2)]
515
+ t.setStyle(TableStyle(style))
516
+ return head + [t] + note
517
+
518
+ def _widths(self, df, numeric, texts: list[list[str]]) -> list[float]:
519
+ """Measured on the FORMATTED text — the raw value is not what prints."""
520
+ from xml.sax.saxutils import unescape
521
+ from reportlab.pdfbase.pdfmetrics import stringWidth
522
+ want = []
523
+ for j, c in enumerate(df.columns):
524
+ font = "IBMPlexMono-Regular" if numeric[c] else "Inter-Regular"
525
+ sample = [unescape(row[j]) for row in texts[:61]]
526
+ w = max(stringWidth(s, font, 8.3) for s in sample) + 14
527
+ want.append(min(max(w, 34), self.width * 0.45))
528
+ total = sum(want)
529
+ if total > self.width:
530
+ return [w * self.width / total for w in want]
531
+ text_cols = [i for i, c in enumerate(df.columns) if not numeric[c]] or [0]
532
+ spare = (self.width - total) / len(text_cols)
533
+ return [w + (spare if i in text_cols else 0) for i, w in enumerate(want)]
534
+
535
+ # charts ------------------------------------------------------------------
536
+ def _style(self):
537
+ import matplotlib as mpl
538
+ return mpl.rc_context({
539
+ "font.family": "Inter", "font.size": 7.5, "axes.edgecolor": LINE,
540
+ "axes.linewidth": 0.6, "axes.labelcolor": DIM, "xtick.color": DIM,
541
+ "ytick.color": DIM, "axes.spines.top": False, "axes.spines.right": False,
542
+ "axes.grid": True, "grid.color": RULE, "grid.linewidth": 0.5, "axes.axisbelow": True,
543
+ "xtick.major.size": 0, "ytick.major.size": 0, "figure.dpi": 100,
544
+ })
545
+
546
+ def _axis_fmt(self, y: str):
547
+ from matplotlib.ticker import FuncFormatter
548
+ # A round tick reads "$300", not "$300.00".
549
+ return FuncFormatter(lambda v, _: fmt(
550
+ v, y, currency=self.rep.currency,
551
+ decimals=0 if y == "pct" or (y != "compact" and float(v).is_integer()) else None))
552
+
553
+ def _image(self, fig, height_mm: float, title: str | None) -> list:
554
+ import matplotlib.pyplot as plt
555
+ from reportlab.platypus import Image, KeepTogether
556
+ buf = io.BytesIO()
557
+ fig.savefig(buf, format="png", dpi=220, bbox_inches="tight", facecolor="white")
558
+ plt.close(fig)
559
+ buf.seek(0)
560
+ img = Image(buf, width=self.width, height=height_mm * self.mm, kind="proportional")
561
+ head = [self._p(escape(title), "caption")] if title else []
562
+ return [KeepTogether(head + [img])]
563
+
564
+ def _chart(self, data: Any, kind: str, title: str | None, y: str, height: float) -> list:
565
+ import matplotlib.pyplot as plt
566
+ pd = self.pd
567
+ df = data.to_frame() if isinstance(data, pd.Series) else self._frame_like(data)
568
+ if df.empty:
569
+ return ([self._p(escape(title), "caption")] if title else []) + \
570
+ [self._p("No data to chart.", "small")]
571
+ with self._style():
572
+ fig, ax = plt.subplots(figsize=(self.width / 72, height / 25.4))
573
+ if kind == "bar" and df.shape[1] == 1:
574
+ s = df.iloc[:, 0]
575
+ ax.bar([str(i) for i in s.index], s.values, width=0.6,
576
+ color=[LOSS if v < 0 else GAIN for v in s.fillna(0).values])
577
+ ax.axhline(0, color=LINE, linewidth=0.8)
578
+ elif kind == "bar":
579
+ df.plot.bar(ax=ax, color=SERIES[:df.shape[1]], width=0.75, legend=True, rot=0)
580
+ else:
581
+ for i, col in enumerate(df.columns):
582
+ color = SERIES[i % len(SERIES)]
583
+ ax.plot(df.index, df[col], color=color, linewidth=1.4, label=str(col))
584
+ if kind == "area":
585
+ ax.fill_between(df.index, df[col], alpha=0.12, color=color)
586
+ if df.shape[1] > 1:
587
+ ax.legend(frameon=False, loc="upper left", ncol=min(4, df.shape[1]))
588
+ ax.yaxis.set_major_formatter(self._axis_fmt(y))
589
+ ax.grid(axis="x", visible=False)
590
+ fig.tight_layout()
591
+ return self._image(fig, height, title)
592
+
593
+ def _frame_like(self, data):
594
+ pd = self.pd
595
+ if isinstance(data, dict):
596
+ return pd.DataFrame(data)
597
+ return data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)
598
+
599
+ def _price(self, data: Any, title: str | None, height: float) -> list:
600
+ import matplotlib.dates as mdates
601
+ import matplotlib.pyplot as plt
602
+ pd = self.pd
603
+ df = self._frame_like(data)
604
+ if df.empty:
605
+ return ([self._p(escape(title), "caption")] if title else []) + \
606
+ [self._p("No data to chart.", "small")]
607
+ df = _dated(pd, df)
608
+ cols = {str(c).lower().replace(" ", "_"): c for c in df.columns}
609
+ close = next((cols[k] for k in ("close", "adj_close", "price", "last") if k in cols), None)
610
+ if close is None or df[close].dropna().empty:
611
+ return ([self._p(escape(title), "caption")] if title else []) + \
612
+ [self._p("No data to chart.", "small")]
613
+ volume = cols.get("volume")
614
+ volume = _stated_volume(pd, df, volume) if volume is not None else None
615
+ with self._style():
616
+ if volume is not None:
617
+ fig, (ax, av) = plt.subplots(2, 1, figsize=(self.width / 72, height / 25.4),
618
+ sharex=True, gridspec_kw={"height_ratios": [3.2, 1]})
619
+ else:
620
+ fig, ax = plt.subplots(figsize=(self.width / 72, height / 25.4))
621
+ av = None
622
+ s = df[close]
623
+ ax.plot(df.index, s, color=AMBER, linewidth=1.4)
624
+ ax.fill_between(df.index, s, s.min(), color=AMBER, alpha=0.08)
625
+ ax.yaxis.tick_right()
626
+ ax.yaxis.set_major_formatter(self._axis_fmt("money" if self.rep.currency else "num"))
627
+ ax.grid(axis="x", visible=False)
628
+ if av is not None:
629
+ av.bar(volume.index, volume.values, color=LINE, width=1.0)
630
+ av.yaxis.tick_right()
631
+ av.yaxis.set_major_formatter(self._axis_fmt("compact"))
632
+ av.grid(visible=False)
633
+ av.set_ylabel("Volume", fontsize=6.5)
634
+ last = ax if av is None else av
635
+ loc = mdates.AutoDateLocator()
636
+ last.xaxis.set_major_locator(loc)
637
+ last.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
638
+ fig.tight_layout(h_pad=0.4)
639
+ return self._image(fig, height, title)
640
+
641
+ def _figure(self, fig, title: str | None, height: float | None) -> list:
642
+ w, h = fig.get_size_inches()
643
+ height = height or (self.width / 72) * (h / w) * 25.4
644
+ return self._image(fig, height, title)