research.sparkline
Documentation for eth_defi.research.sparkline Python module.
Prepare, render and upload share-price sparklines for vault data.
Module Attributes
Versioned visual contract used by canonical input digests and state. |
|
Public sparkline dimensions. |
|
Native 4:1 newsletter/table raster, uniformly scaled from the canonical SVG. |
|
Stable visual style constants shared by direct renderers. |
|
Tolerance used to canonicalise SVG negative zero values. |
Functions
Render a sparkline chart and return as PNG bytes. |
|
Render a sparkline chart and return as SVG bytes. |
|
|
Extract price data for a specific vault from a DataFrame. |
|
Return chart rows with valid timestamps and non-negative finite prices. |
|
Prepare one vault's observations for a fixed-width sparkline. |
|
Render a sparkline chart with green-to-black gradient fill. |
|
Render a deterministic two-times-supersampled Pillow PNG. |
|
Render a simple share-price sparkline for one vault. |
|
Render a deterministic sparse step sparkline as native SVG bytes. |
|
Rasterise the canonical website sparkline for blog and email tables. |
|
Upload a gzip-compressed sparkline image to Cloudflare R2. |
Classes
Pixel coordinates shared by deterministic SVG and PNG renderers. |
|
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:
objectPixel coordinates shared by deterministic SVG and PNG renderers.
- class SparklineData
Bases:
objectDaily closing prices, the initial observation and fixed chart bounds.
Charts span
DEFAULT_SPARKLINE_WINDOWunless 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
prices_df (pandas.DataFrame) –
start_at (pandas.Timestamp) –
end_at (pandas.Timestamp) –
- Return type
None
Return chart rows with valid timestamps and non-negative finite prices.
PyArrow-backed parquet data can expose
share_priceas a nullable or object-backed pandas series. Matplotlib compares y-axis bounds internally, so passingpd.NAthrough causesTypeError: 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_pricecolumn.- Returns
Copy of valid rows with
share_priceconverted to floating point.- Raises
ValueError – If the vault has no finite share-price observations to render.
- Return type
- 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_pricecolumn.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
Nonewhen there are fewer than two distinct valid timestamps or history is too short.- Return type
- extract_vault_price_data(spec, prices_df)
Extract price data for a specific vault from a DataFrame.
- Parameters
spec (eth_defi.vault.base.VaultSpec) – chain-vault address identifier
prices_df (pandas.DataFrame) – DataFrame containing price data
- Returns
Filtered DataFrame for the specified vault
- Return type
- 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
vault_prices_df (Union[pandas.DataFrame, eth_defi.research.sparkline.SparklineData]) – Prepared sparkline data or a finite single-vault price frame.
width (int) – SVG width in pixels.
height (int) – SVG height in pixels.
line_width (int) – Price-line width in pixels.
margin_ratio (int) – Vertical margin in pixels relative to the output height.
line_color (str) – Top colour of the translucent area gradient.
bg_color (str) – Background colour.
x_axis_range (Optional[tuple[pandas.Timestamp, pandas.Timestamp]]) – Optional explicit chart bounds for raw price frames.
- Returns
Stable UTF-8 SVG bytes.
- Return type
- 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_pricecolumn. 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
- 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
vault_prices_df (Union[pandas.DataFrame, eth_defi.research.sparkline.SparklineData]) – Prepared sparkline data or a finite single-vault price frame.
width (int) – Final PNG width in pixels.
height (int) – Final PNG height in pixels.
line_width (int) – Final price-line width in pixels.
margin_ratio (int) – Vertical margin in pixels relative to the output height.
line_color (str) – Top colour of the translucent area gradient.
bg_color (str) – Background colour.
x_axis_range (Optional[tuple[pandas.Timestamp, pandas.Timestamp]]) – Optional explicit chart bounds for raw price frames.
- Returns
Stable PNG bytes.
- Return type
- 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
- 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_pricemust 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
- 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.
- 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
Trueif uploaded,Falseif skipped as unchanged.- Return type