research.sparkline

Documentation for eth_defi.research.sparkline Python module.

Prepare, render and upload share-price sparklines for vault data.

Module Attributes

SPARKLINE_RENDERER_VERSION

Versioned visual contract used by canonical input digests and state.

SPARKLINE_SVG_WIDTH

Public sparkline dimensions.

SPARKLINE_TABLE_PNG_WIDTH

Native 4:1 newsletter/table raster, uniformly scaled from the canonical SVG.

SPARKLINE_LINE_COLOR

Stable visual style constants shared by direct renderers.

SPARKLINE_SVG_NEGATIVE_ZERO_EPSILON

Tolerance used to canonicalise SVG negative zero values.

Functions

export_sparkline_as_png(fig)

Render a sparkline chart and return as PNG bytes.

export_sparkline_as_svg(fig)

Render a sparkline chart and return as SVG bytes.

extract_vault_price_data(spec, prices_df)

Extract price data for a specific vault from a DataFrame.

filter_finite_share_prices(vault_prices_df)

Return chart rows with valid timestamps and non-negative finite prices.

prepare_sparkline_data(vault_prices_df[, ...])

Prepare one vault's observations for a fixed-width sparkline.

render_sparkline_gradient(vault_prices_df[, ...])

Render a sparkline chart with green-to-black gradient fill.

render_sparkline_png(vault_prices_df, *[, ...])

Render a deterministic two-times-supersampled Pillow PNG.

render_sparkline_simple(vault_prices_df[, ...])

Render a simple share-price sparkline for one vault.

render_sparkline_svg(vault_prices_df, *[, ...])

Render a deterministic sparse step sparkline as native SVG bytes.

render_sparkline_table_png(vault_prices_df)

Rasterise the canonical website sparkline for blog and email tables.

upload_to_r2_compressed(payload, ...[, ...])

Upload a gzip-compressed sparkline image to Cloudflare R2.

Classes

SparklineCoordinates

Pixel coordinates shared by deterministic SVG and PNG renderers.

SparklineData

Daily closing prices, the initial observation and fixed chart bounds.

DEFAULT_SPARKLINE_WINDOW = Timedelta('90 days 00:00:00')

Width of the time axis used by published vault sparklines.

MIN_SPARKLINE_HISTORY = Timedelta('0 days 00:00:00')

Optional duration floor. Publication requires two distinct valid timestamps.

SPARKLINE_RENDERER_VERSION = 5

Versioned visual contract used by canonical input digests and state.

SPARKLINE_SVG_WIDTH = 100

Public sparkline dimensions.

SPARKLINE_TABLE_PNG_WIDTH = 300

Native 4:1 newsletter/table raster, uniformly scaled from the canonical SVG.

SPARKLINE_LINE_COLOR = '#00ff88'

Stable visual style constants shared by direct renderers.

SPARKLINE_SVG_NEGATIVE_ZERO_EPSILON = 0.0005

Tolerance used to canonicalise SVG negative zero values.

class SparklineCoordinates

Bases: object

Pixel coordinates shared by deterministic SVG and PNG renderers.

points: tuple[tuple[float, float], ...]

Ordered observation points as (x, y) pixels.

baseline_y: float

Baseline used by the non-constant gradient area.

is_constant: bool

Whether every finite share price has the same value.

__init__(points, baseline_y, is_constant)
Parameters
Return type

None

class SparklineData

Bases: object

Daily closing prices, the initial observation and fixed chart bounds.

Charts span DEFAULT_SPARKLINE_WINDOW unless a caller supplies a different window, and end at the latest valid observation. A younger vault occupies only the right-hand side; the period before its first observation remains blank.

prices_df: pandas.DataFrame

Valid daily closing prices and the initial price. Established sparse vaults include one carried observation at start_at.

start_at: pandas.Timestamp

Inclusive left edge of the chart.

end_at: pandas.Timestamp

Inclusive right edge and latest valid observation timestamp.

__init__(prices_df, start_at, end_at)
Parameters
Return type

None

filter_finite_share_prices(vault_prices_df)

Return chart rows with valid timestamps and non-negative finite prices.

PyArrow-backed parquet data can expose share_price as a nullable or object-backed pandas series. Matplotlib compares y-axis bounds internally, so passing pd.NA through causes TypeError: boolean value of NA is ambiguous.

Zero is a valid complete-loss observation. Negative prices, missing times and non-finite values are excluded consistently from chart eligibility.

Parameters

vault_prices_df (pandas.DataFrame) – Single-vault data indexed by naive UTC timestamps with a numeric or nullable share_price column.

Returns

Copy of valid rows with share_price converted to floating point.

Raises

ValueError – If the vault has no finite share-price observations to render.

Return type

pandas.DataFrame

prepare_sparkline_data(vault_prices_df, minimum_history=Timedelta('0 days 00:00:00'), window=Timedelta('90 days 00:00:00'))

Prepare one vault’s observations for a fixed-width sparkline.

Two valid observations at distinct timestamps suffice, even on the first day. Daily closing observations keep their actual timestamps, and the initial observation is retained so its first day’s movement is visible. Charts retain a 90-day axis by default. Young vaults leave the period before their first observation blank, while older sparse vaults carry their last pre-window value to the left boundary.

Parameters
  • vault_prices_df (pandas.DataFrame) – Single-vault data indexed by naive UTC timestamps with a share_price column.

  • minimum_history (pandas.Timedelta) – Optional elapsed-history floor. Defaults to zero; two distinct valid observation timestamps are still required.

  • window (pandas.Timedelta) – Full elapsed time represented by the horizontal axis.

Returns

Daily closes, initial price and chart bounds, or None when there are fewer than two distinct valid timestamps or history is too short.

Return type

Optional[eth_defi.research.sparkline.SparklineData]

extract_vault_price_data(spec, prices_df)

Extract price data for a specific vault from a DataFrame.

Parameters
Returns

Filtered DataFrame for the specified vault

Return type

pandas.DataFrame

render_sparkline_svg(vault_prices_df, *, width=100, height=25, line_width=1, margin_ratio=4, line_color='#22B452', bg_color='#282827', x_axis_range=None)

Render a deterministic sparse step sparkline as native SVG bytes.

Parameters
Returns

Stable UTF-8 SVG bytes.

Return type

bytes

render_sparkline_table_png(vault_prices_df)

Rasterise the canonical website sparkline for blog and email tables.

Render the 100 x 25 SVG directly onto a 300 x 75 canvas. Uniform scaling preserves the observations, step path, time bounds, vertical padding, gradient and round joins, including a 3 px counterpart of the SVG’s 1 px stroke. Resizing the legacy square PNG would compress these vertically.

See the CairoSVG conversion API.

Parameters

vault_prices_df (Union[pandas.DataFrame, eth_defi.research.sparkline.SparklineData, bytes]) – Prepared sparkline data or a single-vault DataFrame indexed by naive UTC timestamps with a finite numeric share_price column. Canonical SVG bytes are also accepted, allowing publication to rasterise the exact SVG payload it uploads without preparing the observations twice.

Returns

Native 4:1 PNG bytes suitable for a 72 x 18 HTML image.

Return type

bytes

render_sparkline_png(vault_prices_df, *, width=300, height=300, line_width=2, margin_ratio=50, line_color='#22B452', bg_color='#282827', x_axis_range=None)

Render a deterministic two-times-supersampled Pillow PNG.

Parameters
Returns

Stable PNG bytes.

Return type

bytes

render_sparkline_simple(vault_prices_df, width=256, height=64, ffill=True)

Render a simple share-price sparkline for one vault.

Parameters
  • vault_prices_df (pandas.DataFrame) – Single-vault prices indexed by naive UTC timestamps.

  • width (int) – Output width in pixels.

  • height (int) – Output height in pixels.

  • ffill (bool) – Forward-fill sparse observations to an hourly line before rendering.

Returns

Matplotlib figure ready for export.

Return type

Any

render_sparkline_gradient(vault_prices_df, width=300, height=300, ffill=True, line_color='#22B452', bg_color='#282827', line_width=2, margin_ratio=50, x_axis_range=None)

Render a sparkline chart with green-to-black gradient fill.

The optional explicit horizontal range lets callers render a short price history within a longer fixed chart period. Matplotlib leaves time before the first observation blank instead of stretching the available data to fill the canvas.

Parameters
  • vault_prices_df (pandas.DataFrame) – Single-vault prices indexed by naive UTC timestamps. share_price must contain at least one finite observation.

  • width (int) – Output figure width in pixels.

  • height (int) – Output figure height in pixels.

  • ffill (bool) – Forward-fill sparse observations to an hourly line before rendering.

  • line_color (str) – Colour at the top of the gradient fill.

  • bg_color (str) – Figure and axes background colour.

  • line_width (int) – Price line width in pixels.

  • margin_ratio (int) – Vertical margin in pixels relative to the output height.

  • x_axis_range (Optional[tuple[pandas.Timestamp, pandas.Timestamp]]) – Optional inclusive chart bounds. The first value must precede the second and both must be naive UTC timestamps.

Returns

Matplotlib figure ready for PNG or SVG export.

Return type

Any

export_sparkline_as_png(fig)

Render a sparkline chart and return as PNG bytes.

Parameters

fig (Any) –

Return type

bytes

export_sparkline_as_svg(fig)

Render a sparkline chart and return as SVG bytes.

Parameters

fig (Any) –

Return type

bytes

upload_to_r2_compressed(payload, bucket_name, object_name, endpoint_url, access_key_id, secret_access_key, content_type, skip_if_current=False)

Upload a gzip-compressed sparkline image to Cloudflare R2.

The source checksum is calculated before compression so deterministic chart bytes can skip an unchanged remote object.

Parameters
  • payload (bytes) – The bytes data to upload.

  • bucket_name (str) – The name of the R2 bucket.

  • object_name (str) – The destination object name (e.g., “my-image.png”).

  • access_key_id (str) – Your R2 access key ID.

  • secret_access_key (str) – Your R2 secret access key.

  • content_type (str) – The MIME type of the file.

  • skip_if_current (bool) – Skip upload if the remote object already matches the local source payload.

  • endpoint_url (str) –

Returns

True if uploaded, False if skipped as unchanged.

Return type

bool