vault_report.charts
Documentation for eth_defi.vault_report.charts Python module.
Static charts for the monthly vault report.
Charts are Plotly figures rendered to PNG by
Kaleido with headless Chrome, then framed
by eth_defi.vault_report.branding. Styling follows
eth_defi.vault_report.theme:
At most eight categorical series, in the theme’s fixed colour order
Legends with protocol logos instead of plain colour boxes
Benchmarks matching the vaults’ activity: the US Treasury bill for calm yield vaults, BTC and ETH for trading and volatile vaults, see
eth_defi.vault_report.benchmarksPerformance as equity curves in percent of all compared vaults in one chart with a shared axis, yields as dots on a rate scale, and dollar TVL changes as diverging bars
Glowing lines for charts with few series, like the website’s hero charts
eth_defi.vault_report.report.render_report_charts() builds every
chart of the post with the create_*_figure functions, renders it with
render_figure_png() inside one chart_renderer() session and
frames it with eth_defi.vault_report.branding.compose_chart_panel().
Units and coordinates:
Sizes are design pixels. Figures are laid out at
IMAGE_WIDTH, the panel width, and Kaleido exports them ateth_defi.vault_report.branding.CHART_SCALEfor high-density screens, so a layout never needs to know the export resolution.Logos, legends and labels outside the plot area are positioned in Plotly paper coordinates: 0-1 spans the plot area, not the figure, so negative x reaches into the left margin and x above 1 into the right margin. Pixel offsets are converted by dividing by the plot area’s width or height in pixels, the figure size minus its margins. See the Plotly layout reference.
Plotly cannot measure text before rendering, and its legends cannot show images, so custom legends and label columns are laid out in Python. Text widths are measured with Pillow from the same Inter font files that Chrome draws with, see
_measure_text(), so the computed layout matches the rendered image.
Module Attributes
Chart width in design pixels, the same as |
|
Chart height in design pixels; the minimum height of the charts with one row per group, which grow with their rows |
|
Width of charts with a logo legend. |
|
Right margin, in design pixels, reserved for a logo legend before it is measured. |
|
Characters per line of a legend label with a detail or properties; longer vault names wrap. |
|
Font size of the curator, protocol and chain row under a vault name, in design pixels |
|
Height of a property icon, in design pixels; a little taller than the 14 px text, so small marks stay legible |
|
Height of one property row, in design pixels |
|
Gap between a property icon and its text, in design pixels |
|
Gap between two properties on the same row, in design pixels |
|
Widest property icon as a multiple of its height; wider logos are scaled down to fit |
|
Benchmark line dash styles. |
|
Equity index value at the window start. |
|
Candidate y axis ticks of a log-scale equity chart, as equity index values; the ticks inside the axis range are used and labelled as returns, e.g. |
|
Candidate tick steps of a linear equity or Sharpe chart, in percentage points or Sharpe units; the smallest step giving at most seven intervals is used |
|
A TVL change this many times larger than the next largest one is drawn off scale, see |
|
Annualised volatility, as a fraction, below which a vault with a return under 0.1% counts as dormant: its share price has not moved, see |
Functions
|
Draw a line with a soft glow underneath, like the website's hero charts. |
|
Draw a legend with logos in the right margin. |
|
Draw a vault's curator, protocol and chain under its name, each with its icon. |
|
Calculate cumulative performance since a start date. |
|
Calculate a rolling annualised Sharpe ratio from daily prices. |
Keep one headless Chrome running for a batch of chart renders. |
|
|
Draw a dot plot of vault yields per chain or protocol against the Treasury bill. |
|
Draw the best vaults on each chain as a dot plot on a log return scale. |
|
Draw the equity curves of vaults and their benchmarks in one chart. |
|
Draw stacked TVL by protocol or fund with a glowing total line. |
|
Draw a risk/return bubble scatter of vaults. |
|
Draw the largest one-month TVL increases and decreases as diverging bars. |
|
Wrap a number in a legend label in bold and an accent colour, so it stands out from the text. |
|
Flow vault properties into rows that fit a width. |
|
Escape external text, such as vault names, for Plotly text. |
|
Convert logo data URIs to Pillow images for the Pillow-drawn hero image. |
|
Render a figure as a PNG image. |
|
Leave out dormant vaults whose share price has not moved over three months. |
|
Shorten a one-line label with an ellipsis, for labels that must not wrap. |
|
Convert |
|
Remove the transparent margins around logos. |
|
Word-wrap a chart label to Plotly |
Classes
One entry of a custom chart legend, see |
|
One vault in a performance comparison chart. |
|
A vault property shown under the vault name: its curator, protocol or chain. |
- IMAGE_WIDTH = 1400
Chart width in design pixels, the same as
eth_defi.vault_report.branding.PANEL_WIDTH. The blog shows images at about 720 px width, so charts are designed at roughly 2× and their font sizes are about twice the displayed size.
- IMAGE_HEIGHT = 800
Chart height in design pixels; the minimum height of the charts with one row per group, which grow with their rows
- CHOREOGRAPHER_CHROME_PATH = PosixPath('/home/runner/.local/share/choreographer/deps/chrome-linux64/chrome')
Chrome downloaded by
plotly_get_chrome/kaleido_get_chromeon Linux, used whenBROWSER_PATHis not set
- LEGEND_CHART_WIDTH = 1330
Width of charts with a logo legend. The legend margin shrinks to the measured legend, so these charts are drawn narrower to give content about as wide as the panel’s inner width, and every chart is shown at the same scale, see
eth_defi.vault_report.branding.compose_chart_panel().
- LEGEND_MARGIN = 480
Right margin, in design pixels, reserved for a logo legend before it is measured. Wide enough for a 34-character vault name;
add_logo_legend()shrinks the margin to the measured legend.
- LEGEND_LABEL_CHARACTERS = 34
Characters per line of a legend label with a detail or properties; longer vault names wrap. Other labels, such as protocol names, wrap at 24 characters, so short legends stay narrow.
- PROPERTY_FONT_SIZE = 14
Font size of the curator, protocol and chain row under a vault name, in design pixels
- PROPERTY_ICON_SIZE = 17
Height of a property icon, in design pixels; a little taller than the 14 px text, so small marks stay legible
- PROPERTY_ROW_HEIGHT = 21
Height of one property row, in design pixels
- PROPERTY_ICON_GAP = 6
Gap between a property icon and its text, in design pixels
- PROPERTY_GAP = 16
Gap between two properties on the same row, in design pixels
- PROPERTY_MAX_ICON_ASPECT = 2.0
Widest property icon as a multiple of its height; wider logos are scaled down to fit
- class VaultProperty
Bases:
objectA vault property shown under the vault name: its curator, protocol or chain.
Properties are drawn in the order curator, protocol, chain, each with its own icon, see
add_property_rows(). They are made byeth_defi.vault_report.report.make_vault_properties(), which leaves out a curator or chain that repeats the protocol, and their logos are then replaced with trimmed ones bytrim_logos(). Used in the performance chart legends, the inflows and outflows chart and, rasterised, the hero image.- logo_uri: Optional[str]
Logo data URI, see
eth_defi.vault_report.logos, orNoneto draw the text only
- logo_aspect: float
Logo width divided by its height, after
trim_logos()removes its margins
- property icon_size: tuple[float, float]
Drawn icon width and height in pixels.
Icons are
PROPERTY_ICON_SIZEtall; wide logos are scaled down to at mostPROPERTY_MAX_ICON_ASPECTtimes that width. Sizing the box to the trimmed logo’s own shape, rather than drawing every logo in a square, puts every icon the same distance from its text. Wordmark-like logos are capped, so they do not dominate the row.
- class LegendEntry
Bases:
objectOne entry of a custom chart legend, see
add_logo_legend().The order of the content follows the report’s legend rule: the vault name in bold, then its return, then the curator, protocol and chain with icons.
- logo_uri: Optional[str]
Protocol, chain or benchmark logo data URI drawn next to the swatch, or
None
- detail: Optional[str]
Muted line under the label, e.g. the final return. Plotly HTML that is drawn as is, so a number can be highlighted with
highlight_number(); escape any external text in it
- properties: tuple[eth_defi.vault_report.charts.VaultProperty, ...]
Curator, protocol and chain drawn with their icons under the label
- inline: bool
Draw the entry on one row: its logo, label and detail, e.g. for benchmarks, see
add_logo_legend()
- __init__(label, colour, logo_uri=None, dash='solid', detail=None, properties=(), inline=False)
- to_rgba(colour, alpha)
Convert
#rrggbbto a CSSrgba()colour.Plotly takes
rgba()strings for translucent lines, fills and markers, such as the glow under a line, the stacked TVL areas and the bubbles of the risk and return chart, while the themes define opaque hex colours.
- plain_text(text)
Escape external text, such as vault names, for Plotly text.
Plotly reads
<b>,<br>and other tags in text as markup, and decodes HTML entities, so an escaped name is shown exactly as written.
- shorten_text(text, max_length)
Shorten a one-line label with an ellipsis, for labels that must not wrap.
Used for the vault names in the right-hand column of the per-chain chart, where each row has room for exactly two one-line names. Prefer
wrap_label()elsewhere, because the report shows names in full.
- wrap_label(text, width)
Word-wrap a chart label to Plotly
<br>lines without truncating it.Plotly annotations do not wrap text by themselves. Used for the chain and protocol names in the left margin of the dot plots. Each line is escaped, see
plain_text().
- highlight_number(text, theme, value=None)
Wrap a number in a legend label in bold and an accent colour, so it stands out from the text.
Chrome draws the
<b>text in the bundled semibold weight. Used for the returns, Sharpe ratios and TVL amounts in legends and label columns.- Parameters
text (str) – Formatted number, e.g.
+22.6%or$5.5B.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
value (Optional[float]) – Signed value for returns: negative values are red, others green.
Nonefor amounts, which are green.
- Returns
Plotly HTML.
- Return type
- layout_properties(properties, width)
Flow vault properties into rows that fit a width.
A greedy line break: each property, icon plus text, goes on the current row if it fits, otherwise it starts a new row. A row always takes its first property, even if it is wider than
width. Callers use the row count to size the label block before drawing it, andadd_property_rows()draws the same rows.- Parameters
properties (tuple[eth_defi.vault_report.charts.VaultProperty, ...]) – Properties in drawing order.
width (float) – Available width in pixels.
- Returns
Rows of
(property, x offset in pixels).- Return type
list[list[tuple[eth_defi.vault_report.charts.VaultProperty, float]]]
- add_property_rows(fig, properties, theme, x, y, yref, width, x_pixels, y_pixels)
Draw a vault’s curator, protocol and chain under its name, each with its icon.
Each property is a layout image and an annotation, placed from the pixel offsets of
layout_properties(). The layout is in pixels but Plotly places elements in axis or paper units, so the caller passes the pixels per unit of each axis. Used in two coordinate systems: the legends ofadd_logo_legend()use paper y, where one unit is the plot height, and the inflows and outflows chart uses data y, where one unit is one bar row, seecreate_tvl_change_figure().- Parameters
fig (plotly.graph_objs._figure.Figure) – Figure to modify.
properties (tuple[eth_defi.vault_report.charts.VaultProperty, ...]) – Properties in drawing order.
theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
x (float) – Paper x coordinate of the row start.
y (float) – Centre of the first row, in
yrefunits. Further rows go down byPROPERTY_ROW_HEIGHTeach.yref (str) –
paperory.width (float) – Available width in pixels; properties flow to more rows when needed.
x_pixels (float) – Pixels per paper x unit, the plot width.
y_pixels (float) – Pixels per
yrefunit.
- Returns
Number of rows drawn.
- Return type
- add_logo_legend(fig, entries, theme, top=1.0, row_height=0.088, split=False)
Draw a legend with logos in the right margin.
Plotly legends cannot show images, so the legend is drawn with shapes, layout images and annotations. Set the figure size and margins before calling this: the right margin, e.g.
LEGEND_MARGIN, is the room the legend may use, and the plot height is the height it is spread over. Used by the performance charts and the stacked TVL charts.Labels are drawn in bold and word-wrapped to full length. An entry’s detail line, e.g. its return, follows the label, and its curator, protocol and chain come last with their icons, see
add_property_rows(). Entries are spaced at leastrow_heightapart, and further when they need more room; the figure grows taller rather than letting entries overlap. Inline entries, the benchmarks, take one row: logo, name and value.The layout is computed in pixels in three steps, because Plotly positions the elements in paper coordinates of a plot area whose size depends on the legend:
Measure: wrap every label, measure its lines, detail and property rows with the bundled font, and collect each entry’s height and the widest line.
Fit: shrink the right margin to the widest line, so the plot widens into the unused margin and the cropped chart content spans the panel width like every other chart; then spread the entries over the plot height, growing the figure when they do not fit.
Draw: convert the pixel positions to paper coordinates, where x = 1 is the right edge of the plot area and the legend lies beyond it.
Columns, in pixels from the plot’s right edge: the swatch line from 26 to 64, an optional 30 px logo at 76, and the text at 112, or at 76 when no multi-row entry has a logo.
- Parameters
fig (plotly.graph_objs._figure.Figure) – Figure to modify.
entries (list[eth_defi.vault_report.charts.LegendEntry]) – Legend entries from top to bottom.
theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
top (float) – Paper y coordinate of the first entry’s first line. All callers use the default, the top of the plot.
row_height (float) – Minimum paper height of one entry. A legend taller than the plot makes the figure taller.
split (bool) – Lay each entry out in two columns under its label: the detail on the left, and the curator, protocol and chain stacked one per row on the right. Entries become shorter when they have several properties.
- Return type
None
- add_glow_line(fig, x, y, colour, name)
Draw a line with a soft glow underneath, like the website’s hero charts.
Use only for charts with one to three lines; glow adds clutter to busy charts. The glow is a second, 14 px wide trace at 18% opacity under the 4 px line, which reads as a halo without Plotly support for blur. Used for the total line over the stacked TVL charts, see
create_protocol_tvl_figure().- Parameters
fig (plotly.graph_objs._figure.Figure) – Figure to modify.
x (pandas.Index) – X values.
y (numpy.ndarray) – Y values.
colour (str) – Line colour.
name (str) – Series name.
- Return type
None
- class PerformanceSeries
Bases:
objectOne vault in a performance comparison chart.
Built by
eth_defi.vault_report.report.render_report_charts()from the vaults chosen for a best-performing section or for the new vaults chart.- properties: tuple[eth_defi.vault_report.charts.VaultProperty, ...]
Curator, protocol and chain shown under the name in the legend, with trimmed logos
- benchmarks: tuple[str, ...]
Benchmark names the vault is compared with, see
eth_defi.vault_report.benchmarks.select_benchmarks()
- BENCHMARK_DASHES = {'BTC': 'dot', 'ETH': 'dashdot', 'US 3M T-bill': 'dash'}
Benchmark line dash styles. Benchmarks share one neutral colour, so they do not compete with the vault colours, and the dash tells them apart. The order is also the order of the benchmark rows in the legend.
- EQUITY_CURVE_BASE = 100
Equity index value at the window start. Lines are plotted as an index, so a log axis works, and labelled in equity %. The index is the value of 100 invested at the window start, so +100% is 200 and -50% is 50, and a log axis shows equal ratios, such as doubling and halving, as equal distances; percentages around 0 have no logarithm.
- LOG_SCALE_TICKS = (10, 20, 50, 80, 100, 120, 150, 200, 300, 400, 500, 1000, 2000, 5000, 10000, 20000, 50000)
Candidate y axis ticks of a log-scale equity chart, as equity index values; the ticks inside the axis range are used and labelled as returns, e.g. 80 as -20% and 500 as +400%. Plotly’s own log ticks would label the index values, or leave the 2 and 5 minor ticks unlabelled.
- LINEAR_TICK_STEPS = (0.2, 0.5, 1, 2, 5, 10, 20, 25, 50, 100, 200, 500)
Candidate tick steps of a linear equity or Sharpe chart, in percentage points or Sharpe units; the smallest step giving at most seven intervals is used
- calculate_period_performance(series, start_at)
Calculate cumulative performance since a start date.
A vault that launched after
start_atstarts from its first data point, so every equity curve starts at 0% wherever it starts in time.- Parameters
series (pandas.Series) – Daily share prices from
eth_defi.vault_report.data.calculate_daily_share_prices(), or benchmark values reindexed to the same days.start_at (pandas.Timestamp) – Start of the period.
- Returns
Cumulative return in percent, starting at 0.
- Return type
- calculate_rolling_sharpe(prices, window=datetime.timedelta(days=90), min_periods=30)
Calculate a rolling annualised Sharpe ratio from daily prices.
Uses the same method as the exported three-month Sharpe ratio, see
eth_defi.research.vault_metrics.calculate_sharpe_ratio_from_returns(): daily percentage returns, mean over standard deviation, annualised with 365 days and a zero risk-free rate. The input must be forward filled, not interpolated, like the exporter’s daily prices, so the values match the tables’ “3M Sharpe” column.- Parameters
prices (pandas.Series) – Forward-filled daily share prices or benchmark values.
window (datetime.timedelta) – Rolling window.
min_periods (int) – Minimum number of daily returns before a value is drawn.
- Returns
Rolling Sharpe ratio, without undefined values.
- Return type
- create_performance_figure(series, daily_prices, benchmark_indices, theme, window=datetime.timedelta(days=90), log_threshold=100.0, outlier_ratio=3.0, benchmark_logos=None, measure='equity', sharpe_window=datetime.timedelta(days=90), split_legend=False)
Draw the equity curves of vaults and their benchmarks in one chart.
Each line shows the equity change in percent since the start of the window. All vaults share the time axis and the equity axis, so their equity curves can be compared directly. Vault colours follow the ranking order, and the legend numbers are the ranks. The legend and line end labels show annualised returns over each line’s span, as bare percentages; the chart subtitle says they are annualised. A vault younger than the window starts from 0% at its first data point.
Benchmarks used by at least half of the vaults, see
eth_defi.vault_report.benchmarks.select_benchmarks(), are drawn once in a neutral colour and rebased to the window start. A single volatile vault among calm ones therefore does not pull BTC and ETH into a T-bill chart.A vault whose peak return exceeds
outlier_ratiotimes the median vault peak, the benchmark peaks and 10% is drawn off scale: the axis fits the other lines, and the outlier leaves the top edge with a marker, repeated as ▲ in the legend. Otherwise one anomalous vault would flatten all others.When the remaining lines return more than
log_thresholdpercent, the y axis switches to a log scale.Use cases:
eth_defi.vault_report.report.render_report_charts()draws one chart per best-performing section of the post, over the 90-day performance window, and the new vaults chart, whose window is the new vault age limit. The perp DEX Sharpe ratio section usesmeasure="sharpe"with the split legend.Layout, in design pixels: the figure is
LEGEND_CHART_WIDTHwide, with the y axis title and ticks in a 110 px left margin and the logo legend in the right margin, seeadd_logo_legend(). The x axis runs 16% of the window past the data date, so the direct labels at the line ends fit inside the plot. Each vault line ends in a dot and a rank badge in its colour, matching the legend numbers; each benchmark line ends in its logo and value. The labels are pushed apart vertically so they never overlap, keeping their order. :param series:Vaults in table order, at most as many as the theme has series colours.
- Parameters
daily_prices (pandas.DataFrame) – Output of
eth_defi.vault_report.data.calculate_daily_share_prices(): a dailyDatetimeIndexand one share price column per vault id. Its last day is the end of the chart.benchmark_indices (dict[str, pandas.Series]) – Output of
eth_defi.vault_report.benchmarks.fetch_benchmark_indices(): benchmark name -> daily value series.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
window (datetime.timedelta) – Performance period.
log_threshold (float) – Cumulative return in percent above which the y axis is logarithmic.
outlier_ratio (float) – Peak return multiple of the median vault peak above which a vault is drawn off scale.
benchmark_logos (Optional[dict[str, str | None]]) – Benchmark name -> logo data URI, see
eth_defi.vault_report.logos.load_benchmark_logo_uri(). Drawn in the legend and at the benchmark line ends.measure (Literal['equity', 'sharpe']) –
equitydraws equity curves.sharpedraws the rolling Sharpe ratio oversharpe_windowinstead, seecalculate_rolling_sharpe();daily_pricesmust then be forward filled and cover the window before the chart start. The legend shows the latest value, and the US Treasury bill, which has no volatility, is left out.sharpe_window (datetime.timedelta) – Rolling window of the Sharpe ratio.
split_legend (bool) – Use the two-column legend entries, see
add_logo_legend().series (list[eth_defi.vault_report.charts.PerformanceSeries]) –
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- create_average_yield_figure(yields, vault_returns, group_column, theme, logos=None, benchmark_yield=None, max_return=0.4)
Draw a dot plot of vault yields per chain or protocol against the Treasury bill.
A yield is a position on a rate scale, not a quantity, so each group is a row of dots rather than a bar: small dots for individual vaults, showing the spread, and a large dot for the TVL-weighted average. The right-hand column gives the average, its difference to the Treasury bill in percentage points, and the group’s TVL.
Beating the risk-free rate is the point of a stablecoin vault, so an average dot is green when it is at or above the Treasury bill yield and grey below it, and the bill is drawn as an amber reference line. The vault dots are translucent grey, so dense clusters show as darker areas.
The x axis fits the averages and most vault dots, so a few outlier vaults do not squeeze the scale. It reaches up to the 90th percentile vault, but at most twice the highest average, and always includes 1.25 times the highest average, 1.5 times the Treasury bill yield and 2%, never beyond
max_return. It reaches down to the 5th percentile vault, but no lower than -5%, and always includes 0% and the lowest average. Vault dots outside the axis are left out of the chart but still counted in the averages.Use cases: the Yield by chain and protocol section of the post, with the largest blockchains, the largest protocols and the highest-yielding protocols, see
eth_defi.vault_report.report.render_report_charts().Layout, in design pixels: groups are rows, the highest average at the top, 58 px apart, and the figure grows beyond
IMAGE_HEIGHTfor more rows. The 254 px left margin holds each group’s logo and wrapped name; the 264 px right margin holds the value column. Both are placed in paper x, negative into the left margin and above 1 into the right one.- Parameters
yields (pandas.DataFrame) – Output of
eth_defi.vault_report.sections.calculate_chain_yields(),calculate_protocol_yields()orcalculate_high_yield_protocols(): indexed by group name, withtvlin USD andavg_returnas a fraction.vault_returns (pandas.DataFrame) – Vaults counted in the averages, indexed by vault id, with the
group_columnandthree_months_cagr_bestcolumns, seeeth_defi.vault_report.sections.select_average_yield_vaults().group_column (str) –
chainorprotocol.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
logos (Optional[dict[str, str | None]]) – Group name -> logo data URI.
benchmark_yield (Optional[float]) – Latest US Treasury bill yield as a fraction.
max_return (float) – Upper limit of the x axis as an annualised return.
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- create_chain_best_figure(chain_vaults, theme, logos=None, benchmark_yield=None)
Draw the best vaults on each chain as a dot plot on a log return scale.
Each chain is a row, sorted by its best vault’s return. The two best vaults are large green dots, the runners-up small grey dots, and the right-hand column names the two best vaults and their returns. The best vaults range from money market yields to capped trading returns, so the return axis is logarithmic.
A log axis cannot show zero or negative returns, so returns below 0.1% are drawn at that floor, on the left edge. The axis reaches 1.6 times the best return, at least 20%, with decade ticks labelled in percent.
Used for the Vaults on each chain subsection, which names the two best vaults on each chain. The 200 px left margin holds the chain logos and names, and the 390 px right margin the two vault names per row, each shortened to one line so a row’s two lines fit its 64 px height.
- Parameters
chain_vaults (pandas.DataFrame) – Output of
eth_defi.vault_report.sections.select_chain_chart_vaults(), withchain,nameandthree_months_cagr_bestcolumns, best first within each chain.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
logos (Optional[dict[str, str | None]]) – Chain name -> logo data URI.
benchmark_yield (Optional[float]) – Latest US Treasury bill yield as a fraction, drawn as a reference line.
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- TVL_CHANGE_OUTLIER_RATIO = 3
A TVL change this many times larger than the next largest one is drawn off scale, see
create_tvl_change_figure(). For example, one fund share class minting billions would otherwise flatten every other bar.
- create_tvl_change_figure(changes, theme, properties=None, logos=None)
Draw the largest one-month TVL increases and decreases as diverging bars.
Dollar amounts are quantities, so bars are the right form here: increases extend right in green, decreases left in red, with the amount labelled.
TVL changes include returns as well as deposits and redemptions, because the export’s net flow estimates cover too few vaults, see
README-blog-post-outline.md. The x axis is symmetric around $0 and fits the largest change, or the second largest when the largest isTVL_CHANGE_OUTLIER_RATIOtimes bigger. An off-scale bar is cut just inside the axis edge, and its label gets a ◀ or ▶ arrow.Used for the two charts of the Inflows and outflows section: by vault, with each vault’s curator, protocol and chain under its name, and by blockchain, with a chain logo before each name.
Layout, in design pixels: one row per vault, 72 px apart, largest increase at the top, the figure growing beyond
IMAGE_HEIGHTfor more rows. The 470 px left margin holds the label blocks: the name wrapped at 40 characters on 21 px lines, then the property rows, centred vertically on the bar. Label blocks are placed in data y, where one unit is one row, so pixel heights are divided by the pixels per row.- Parameters
changes (pandas.DataFrame) – Output of
eth_defi.vault_report.sections.calculate_tvl_changes()orcalculate_chain_tvl_changes(), largest increase first, withtvl_changein USD. Vault rows also neednameandaddress; chain rows are indexed by chain name.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
properties (Optional[dict[str, tuple[eth_defi.vault_report.charts.VaultProperty, ...]]]) – Vault id -> curator, protocol and chain, drawn with their icons under the vault name.
logos (Optional[dict[str, str | None]]) – Row index -> logo data URI drawn before the name, e.g. chain logos when the rows are blockchains.
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- DORMANT_VOLATILITY = 1e-05
Annualised volatility, as a fraction, below which a vault with a return under 0.1% counts as dormant: its share price has not moved, see
select_moving_vaults()
- select_moving_vaults(vaults_df)
Leave out dormant vaults whose share price has not moved over three months.
Vaults with practically zero volatility and zero return, e.g. idle or wound-down vaults, would pile up as a vertical stripe on the left edge of a log-scale risk and return chart.
- Parameters
vaults_df (pandas.DataFrame) – Vaults with
three_months_volatilityandthree_months_cagr_best.- Returns
Vaults with a moving share price.
- Return type
- create_risk_return_figure(vaults_df, category_labels, theme, max_return, benchmark_yield=None)
Draw a risk/return bubble scatter of vaults.
Uses annualised three-month volatility rather than Sharpe, because near-zero-volatility lending vaults have Sharpe ratios in the millions.
The axes are fitted to the bulk of the vaults, so the dense middle of the market is readable. The logarithmic x axis runs from 0.01% volatility to twice the 98th percentile volatility, at least 1% and at most 100%. The y axis runs from the 1st percentile return, no higher than 0% and with 2 percentage points of room, floored at -15%, to 1.1 times the 99th percentile return, at least three times the T-bill yield and 10%, and at most
max_return. Vaults outside the axes are left out of the chart. Large bubbles are drawn first and are translucent, so small vaults on top of them stay visible. Unclassified vaults are drawn in a neutral colour, so classified strategies stand out. Vaults are not labelled: the chart shows strategy categories, not individual vaults.- Parameters
vaults_df (pandas.DataFrame) – Vaults with
three_months_volatility,three_months_cagr_best,current_navandstrategy_tagscolumns, seeselect_moving_vaults().category_labels (dict[str, str]) – Strategy tag -> human-readable category label.
theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
max_return (float) – Upper limit of the return axis, as a fraction.
benchmark_yield (Optional[float]) – Latest US Treasury bill yield as a fraction, drawn as a reference line.
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- create_protocol_tvl_figure(tvl_by_protocol, theme, logos=None, value_label='TVL')
Draw stacked TVL by protocol or fund with a glowing total line.
- Parameters
tvl_by_protocol (pandas.DataFrame) – Periodic TVL in USD, one column per protocol or fund in stacking order (largest first), with at most seven groups and
Other.theme (eth_defi.vault_report.theme.ChartTheme) – Chart theme.
logos (Optional[dict[str, str | None]]) – Protocol or fund name -> logo data URI.
value_label (str) – Name of the value on the y axis, e.g.
TVLorNAV.
- Returns
Plotly figure.
- Return type
plotly.graph_objs._figure.Figure
- rasterise_logos(logo_uris, size=96, columns=16)
Convert logo data URIs to Pillow images for the Pillow-drawn hero image.
PNG logos are decoded directly. SVG logos, such as the website’s chain logos, are rendered by Kaleido in one pass: Pillow cannot draw SVG.
- trim_logos(logo_uris, size=96)
Remove the transparent margins around logos.
Logo files come with different amounts of empty space around the mark, so icons drawn in same-sized boxes look unevenly spaced from their text. The logos are rasterised, cropped to their visible pixels and re-encoded as PNG, and their aspect ratio sizes each icon box to the mark itself.
- chart_renderer()
Keep one headless Chrome running for a batch of chart renders.
Without it, Kaleido starts a new browser for every image, which took about 1 second per chart in September 2026 against 0.4 seconds with a shared browser. See the Kaleido documentation.
- Return type
collections.abc.Iterator[None]
- render_figure_png(fig, path, scale=1.0)
Render a figure as a PNG image.
Kaleido 1.x renders images with a headless Chrome. If
BROWSER_PATHis not set and Chrome has been downloaded withplotly_get_chrometo the default choreographer location, that Chrome is used. The bundledFONT_FAMILYfont is made available to Chrome, see_configure_fonts().The chart is rendered on a transparent background, so the panel surface and its corner glow show through evenly when
eth_defi.vault_report.branding.compose_chart_panel()frames it.- Parameters
fig (plotly.graph_objs._figure.Figure) – Plotly figure with width and height set in its layout.
path (pathlib.Path) – Output file.
scale (float) – Resolution multiplier; the layout keeps its size in design pixels.
- Returns
The output path.
- Return type