Documents
A report is built once as an immutable Document, then rendered as many ways as it is
needed. HtmlBuilder has one method per component. Each call returns the builder, so
calls chain, and .build() freezes the result.
from common_reports import EmailRenderer, HtmlBuilder
doc = ( HtmlBuilder("Daily Update") .frontmatter(title="Daily Update", date="30 Sep 2026") .text("Orders for **Genesis** were sent at 15:45 ET.") .section("Positions") .table(positions_df) .build())
email = doc.render(EmailRenderer(style="modern")) # or doc.to_email(style="modern")page = doc.to_html(style="modern") # a standalone interactive pageHtmlBuilder, col, EmailClient and the three renderers are exported from
common_reports. The component and format types (Kpi, TableFormat, ColumnFormat,
PlotType, PlotFormat, Brand and the rest) come from
common_reports.contracts.builders.
Frontmatter
b.frontmatter(title="Portfolio Report", date="30 Sep 2026", preheader="NAV +0.42% today")The modern style reads title and date for the masthead, and labels (one string
or several) for small pills above the title, such as labels=("Fund launch 24 Jun 2026",). It reads preheader for the
one-line preview mail apps show next to the subject. A renderer argument of the same
name wins over the frontmatter value.
Text
| Method | Draws |
|---|---|
heading(text, level=2) | a heading with an anchor id |
text(content, fmt="prose") | a paragraph block; the formats are below |
caption(text) | small muted text under a table or chart |
disclaimer(text=None) | the standard past-performance disclaimer, or your own |
raw_html(html) | trusted HTML, not escaped; you own sanitizing it |
text() formats split the content on its lines:
fmt | Result |
|---|---|
prose | paragraphs; a blank line starts a new one |
bullets, dashed, numbered | one list item per line; a leading - is dropped |
kv, labeled | a two-column list from Label: value lines |
indented | prose with a left indent |
All text is escaped. The modern style then applies a small markdown set: **bold**,
*italic*, `code` and [text](https://...) links.
b.text("Job: prices_daily\nRun: `a1b2c3`\nStarted: 06:05 ET", fmt="kv")Alert components
| Method | Draws |
|---|---|
callout(text, tone="info", title=None) | a tinted box with a coloured edge |
status(text, tone="info") | a small tag such as FILLED, FAILED or LIVE |
button(text, url) | a link drawn as a button; https://, http:// or mailto: only |
The tones are info, success, warning and danger. Any other value raises
ValueError.
Headline numbers
from common_reports.contracts.builders import Kpi, NumberFormat
b.kpis( Kpi("NAV", 1_250_000, fmt=NumberFormat.DOLLAR, change=0.0042), Kpi("Day P&L", 5_210, fmt=NumberFormat.DOLLAR, note="vs 4,900 est."), Kpi("Gross exposure", 1.42, fmt=NumberFormat.RATIO, trend=(1.30, 1.35, 1.38, 1.42)), ("Positions", 37), # a plain (label, value) pair)Kpi field | Meaning |
|---|---|
label, value | the tile’s name and number |
fmt, decimals | how the value is formatted (PERCENT, DOLLAR, RATIO, INT, FLOAT, DATE, TEXT) |
change, change_fmt | a signed change under the value, green or red; percent by default |
note | a short muted line |
trend | recent values, drawn as a small bar sparkline |
compare | any number of (label, signed value) lines, each a coloured arrow line: (("Nasdaq", 0.0081), ("Meta", 0.002)) |
signed | the headline is itself a change (a day’s return): drawn with its sign in the up/down colour (modern and classic) |
Tables
from common_reports.contracts.builders import ColumnFormat, NumberFormat, TableFormat
b.table( fills_df, caption="Fills, 30 Sep 2026", fmt=TableFormat( columns={ "Weight": ColumnFormat("Weight", num_fmt=NumberFormat.PERCENT, bar=True), "Status": ColumnFormat("Status", tones={"FILLED": "success", "REJECTED": "danger"}), "Fill time": ColumnFormat("Fill time", num_fmt=NumberFormat.DATE, null_display="—"), }, ),)A column’s number format is resolved in this order:
- A
ColumnFormatfor that column. - Membership in the label sets (
percent_labels,dollar_labels,ratio_labels,int_labels). Membership is an exact match on the label, never a substring. - Modern style only: a guess from the column name.
- Weight, return, exposure and similar words give percent. The guess is withheld when values are already above 10, so 25.0 is not shown as 2,500%.
- P&L, value, price, NAV and cash give dollars.
- Qty, shares and volume give whole numbers.
default_num_fmt(FLOAT, 2 decimals).
Columns whose sign carries meaning (P&L, return, change, alpha, gain) are coloured green or red in the modern style.
Useful ColumnFormat fields:
num_fmt,decimals,scale:scalemultiplies the value before formatting.align,width.null_display: shown for missing values, dates included.color: aColorRule.tones: maps a value to a status tone and draws it as a tag.bar: draws a bar under each value, scaled to the column.highlight: tints the whole column, for example the fund in a comparison (modern).width: a fixed width such as"14%"(modern). Give the same widths to tables drawn one after another and their columns line up;ColumnFormat("__index__", width=...)sizes the label column.formatter: a callable, as an escape hatch.
Table-wide settings on TableFormat:
index: anIndexSpecthat resets, bolds and labels the index.header: aHeaderStylewith sticky headers and renames.colors: rules such as a heatmap gradient.total_row,total_col.na_fill.rows: aRowFormatper row label, for tables where rows are metrics (below).column_lines: thin vertical lines between columns (modern).compact: denser rows with 12px values (modern).
On a phone (screens up to 560px wide), modern email tables tighten their cells to 10px figures and let nested sublines wrap, so a 7-column comparison table fits the screen. Phones are also told not to enlarge table text on their own.
Comparison tables: rows are metrics
When each row is a metric and each column is something being compared (strategies, a
fund, benchmarks), give the rows their own look with RowFormat, keyed by the row label.
These settings apply in the modern style.
RowFormat field | Effect |
|---|---|
group | a small heading drawn above the first row of each group |
signed | values coloured by sign: green up, red down |
best | "max" or "min": the best value in the row is bold; values that read the same are all bold |
bar | a bar under each value, scaled to the row’s largest magnitude |
Number formats still come from the label sets, with scope=Scope.BY_ROW (the default).
One metric over several periods. Give the table a two-level row index (metric,
period) and set IndexSpec(multiindex="nested"). Each metric is drawn once in bold, with
its periods as indented lines under it. A row whose period is empty is a single line, so
each metric chooses its own periods. RowFormat is keyed by the metric and applies to
each of its lines; best and bar work line by line.
import pandas as pd
from common_reports.contracts.builders import ColumnFormat, IndexSpec, RowFormat, TableFormat
L, P = "Since fund launch", "Since live production"perf = pd.DataFrame( [ [0.031, 0.096, 0.078, 0.053], [1.527, 2.108, None, 0.676], [0.138, 0.374, 0.078, 0.221], [1.15, 2.81, 2.35, 1.09], [1.65, 1.89, None, 1.13], ], index=pd.MultiIndex.from_tuples( [("Returns", L), ("Returns", P), ("YTD", ""), ("Sharpe", L), ("Sharpe", P)] ), columns=["Core", "Meta", "Fund", "Nasdaq"],)b.table( perf, fmt=TableFormat( percent_labels=frozenset({"Returns", "YTD"}), ratio_labels=frozenset({"Sharpe"}), index=IndexSpec(multiindex="nested"), columns={"Fund": ColumnFormat("Fund", highlight=True)}, rows={ "Returns": RowFormat("Returns", group="Performance", signed=True, best="max", bar=True), "YTD": RowFormat("YTD", group="Performance", signed=True, best="max"), "Sharpe": RowFormat("Sharpe", group="Risk-adjusted", best="max"), }, ),)Stacked cells
A cell can hold a short list instead of one value: give it a tuple of CellLine. Each line
is drawn at a fixed height, so lists in neighbouring cells stay level, which lets one row
per holder carry a line per ticker.
CellLine field | Draws |
|---|---|
label | the line’s name, first (e.g. a ticker) |
value + signed | a number in the column’s num_fmt; signed=True adds a coloured ▲ / ▼ |
tag + tone | a status tag |
text | plain text |
bar | a small bar, 0 to 1 |
from common_reports.contracts.builders import CellLine
holdings = pd.DataFrame( { "Day return": [ ( CellLine("TECL", value=0.0216, signed=True), CellLine("XLE", value=-0.0109, signed=True), ) ] }, index=["Fund"],)b.table( holdings, fmt=TableFormat( columns={"Day return": ColumnFormat("Day return", num_fmt=NumberFormat.PERCENT)} ),)Charts and images
| Method | Draws |
|---|---|
plot(df, type=PlotType..., fmt=PlotFormat(...), caption=...) | a chart from data; see Charts |
figure(plotly_fig, caption=...) | a Plotly figure you built yourself |
image(src, alt="", width=None) | a path, URL or PNG bytes |
Emails carry charts as images. The interactive page keeps them live.
Layout
from common_reports import HtmlBuilder, colfrom common_reports.contracts.builders import PlotFormat, PlotType
b.section("Risk") # later calls go inside until the next sectionb.row( col(lambda c: c.kpis(("Vol", "12.1%"), ("Beta", "0.84"))), col( lambda c: c.plot( returns_df, type=PlotType.UNDERWATER, fmt=PlotFormat(strat_cols=("Genesis",)) ), weight=2, ),)b.end_section() # optional; build() closes the open sectionb.divider()b.spacer("lg")section(title, collapsible=False, show=True, render_figures=True)groups what follows it. The sections also make up the page’s table of contents.show=Falsedrops the section from the render.render_figures=Falserenders it without its charts.row(*cells),columns(n, *cells, widths=[...])andgrid(*cells, cols=2)lay components side by side.- Each cell is
col(fn, weight=1, width=None), or a bare component. In email, cells stack into one column on phones. divider()andspacer(size)separate blocks. The spacer sizes arexs,sm,md,lgandxl.
Placeholders
Write a document once and fill it later. {key} placeholders are replaced in text,
headings, captions, callouts, status tags, buttons and KPI labels.
template = HtmlBuilder("Run report").heading("Run {run_id}").text("Finished at {time}.").build()doc = template.fill(run_id="a1b2c3", time="06:12 ET")assert doc.unfilled == [] # keys still open anywhere in the tree (frontmatter is not filled)Rendering
| Call | Output |
|---|---|
doc.render(EmailRenderer(...)) / doc.to_email(...) | RenderResult with .html and .attachments (inline images) |
doc.render(InteractiveHtmlRenderer(...)) / doc.to_html(...) | RenderResult for a standalone page; .save(path) writes it |
doc.render(GhostRenderer(uploader=...)) / doc.to_ghost(...) | a Ghost post in manifest["ghost_post"] (classic only) |
RenderResult.manifest reports size_bytes and gmail_clip_risk. Gmail hides message
HTML past about 102 KB behind “View entire message”.