research.vault_metrics
Documentation for eth_defi.research.vault_metrics Python module.
Vault metrics calculations.
Calculate various performance reports and charts for vaults.
Module Attributes
Cleaned-price columns not used by daily returns or lifetime metrics. |
|
Vaults with TVL above this are considered broken smart contracts |
|
Vaults with share price above this are considered broken smart contracts |
|
Vaults with annualised volatility above this are considered broken. |
|
Two real observations establish an absolute return and a launch-day basis. |
|
The daily bundle may retain its initial observation and first day's close. |
|
Minimum price observations required before reporting a Sharpe ratio. |
|
Human-readable note suffixes for vault scan cycles slower than active hourly scans. |
|
USD metrics cannot be calculated because an ETH/BTC rate series is absent. |
|
USD metrics cannot be calculated because an ETH/BTC rate series failed validation. |
|
USD metrics cannot be calculated without a contiguous bounded rate window. |
|
Period -> period duration, max sparse sample mismatch |
|
Daily directional-flow columns supplied by protocol data sources. |
|
Daily signed flow used when gross directional events are unavailable. |
|
Daily event-count columns required before gross flows may be published. |
|
Vault accounting columns required for an ERC-4626 flow estimate. |
|
Maximum relative divergence between total assets and supply times share price. |
|
Whether a regular daily row contains one fresh, complete vault state. |
|
Nanoseconds in one calendar day, the unit of the integer timestamps below. |
|
Numeric price columns that the metric calculations read as arrays. |
|
Protocol slugs for vaults where we do not necessarily have on-chain deposit/redeem event data. |
|
Group headings for FFN performance stats, matching the None separators in |
Functions
|
Create charts and tables to analyse a vault performance. |
|
Check for broken vaults by detecting abnormal metric values. |
|
Blacklist vaults that carry scanned bad flags. |
|
Blacklist Morpho vaults missing from Morpho API. |
Calculate annualised volatility from regular daily returns. |
|
Calculate JSON-only USD period metrics for an ETH/BTC crypto vault. |
|
|
Takes a returns series and calculates cumulative returns. |
Calculate consecutive calendar-day returns for each vault. |
|
Calculate consecutive daily returns under a historical API name. |
|
|
Calculate lifetime metrics for each vault in the provided DataFrame. |
|
Calculate profit after external fees have been reduced from the share price change. |
|
Convert a cumulative gross return series to a cumulative net return series after fees. |
|
Convert a share price series to net return series after fees. |
Calculate performance metrics for each vault. |
|
|
Calculate metrics for one period. |
|
Calculate every established period from paired sparse and daily inputs. |
|
Calculate regular period returns from share-price observations. |
|
Calculate annualised Sharpe ratio from regular daily returns. |
Regularise daily closing observations for lifetime metric states. |
|
|
Calculate rankings for all periods inside PeriodMetrics objects. |
|
Process a single vault metadata + prices to calculate its full data. |
|
Filter lifetime metrics by NAV, activity and available annualised returns. |
|
Create combined net / (gross) returns column for display. |
|
Create 2% / 20% style labels to display variosu kinds of vault fees. |
|
Check that each price identity has a vault metadata entry. |
Render a formatted lifetime table as compact HTML in a Jupyter notebook. |
|
|
Render a chart and tearsheet for a single vault. |
|
Export lifetime metrics row to a fully JSON-serialisable dict. |
|
Append lower scan-cycle context to a vault note. |
Display fees to .1 accuracy if there are .1 fractions, otherwise as int. |
|
|
Create a generic note for vaults that carry bad scan flags. |
|
Format FFN report for human readable output. |
Format FFN report as logically grouped sections. |
|
|
Format table for human readable output. |
|
Format vault database for human readable output. |
|
Format vault header for human readable output. |
|
Get the latest known vault scan cycle from price rows. |
|
Get PeriodMetrics for a specific period from the results list. |
|
Check if a vault is a special vault that may not have deposit/redeem event data. |
|
Build generic vault warning display entries for JSON export. |
Normalise a raw vault scan cycle value. |
|
Create one regular daily price and return series from sparse observations. |
|
|
Calculate regular period returns from a finer-grained return series. |
|
Create a slug from protocol name for URLs. |
|
Create a slug from vault metadata for URLs. |
|
Create slugs for a set of vaults. |
|
Replace values with abs(x) < eps by 0. |
Classes
Cleaned ETH/BTC USD-rate inputs for one crypto metadata build. |
|
Provenance metadata for the vault metrics JSON export. |
|
Git version stamp of the exporter Docker image. |
|
Deprecated legacy top-level deposit and withdrawal flow metrics. |
|
Tearsheet metrics for one period. |
|
One public strategy category and its aggregate vault metrics. |
|
USD-converted period metrics for one ETH/BTC vault period. |
|
Top-level structure of the vault metrics JSON export. |
|
Per-vault record in the JSON export. |
|
One vault data analysed |
|
Vault-wide KYC status and its qualification notes. |
- UNUSED_METRIC_PRICE_COLUMNS = frozenset({'avg_assets_by_vault', 'dynamic_tvl_threshold', 'epoch_reset', 'errors', 'hypercore_repair_status', 'hypercore_source', 'management_fee', 'max_deposit', 'max_redeem', 'name', 'performance_fee', 'protocol', 'raw_share_price', 'redemption_open', 'returns_1h', 'trading', 'tvl_filtering_mask', 'vault_settlement_at', 'written_at'})
Cleaned-price columns not used by daily returns or lifetime metrics. Select by exclusion so future price fields remain available by default.
- Percent
Percent as the floating point.
0.01 = 1%
- FeeInput: TypeAlias = float | decimal.Decimal | typing.Literal['-'] | None
Fee values as received from current and legacy vault metadata.
The exported metadata normally uses floats, but cached database rows can contain
decimal.Decimalvalues after JSON/YAML deserialisation.
- MAX_VALID_NAV: float = 100000000000
Vaults with TVL above this are considered broken smart contracts
- MAX_VALID_SHARE_PRICE: float = 1000000
Vaults with share price above this are considered broken smart contracts
- MAX_VALID_VOLATILITY: float = 10000
Vaults with annualised volatility above this are considered broken. This catches low-TVL Hyperliquid vaults with one or few trades that produce extreme volatility numbers.
- MINIMUM_SHARPE_SAMPLE_DURATION = Timedelta('14 days 00:00:00')
Minimum calendar duration required before reporting a Sharpe ratio.
Short-lived vaults can show mechanically extreme annualised Sharpe ratios because a few nearly identical price observations imply implausibly low volatility. This is a data-quality floor, not a claim that two weeks is a statistically sufficient track record.
- MINIMUM_LIFETIME_CAGR_SAMPLE_DURATION = Timedelta('30 days 00:00:00')
Lifetime CAGR requires a month of actual history. Fixed lookbacks require their complete requested period; absolute returns remain available sooner.
- MINIMUM_RETURN_OBSERVATIONS = 2
Two real observations establish an absolute return and a launch-day basis.
- INITIAL_DAY_PRICE_OBSERVATIONS = 2
The daily bundle may retain its initial observation and first day’s close.
- MINIMUM_SHARPE_PRICE_SAMPLES = 10
Minimum price observations required before reporting a Sharpe ratio.
The duration floor alone does not reject a sparse series. Ten prices yield nine returns, enough to avoid ranking a vault from only a handful of moves.
- VAULT_SCAN_CYCLE_NOTES = {'early': 'The vault data might be updated infrequently because the vault has low TVL and is still in the initial sampling period.', 'faded': 'The vault data might be updated infrequently because the vault has not reached sustained TVL traction.', 'peaked': 'The vault data might be updated infrequently because the vault TVL has fallen substantially from its historical peak.', 'small_tvl': 'The vault data might be updated infrequently because the vault TVL is below the active-vault threshold.', 'tiny_tvl': 'The vault data might be updated infrequently because the vault current TVL is very small.'}
Human-readable note suffixes for vault scan cycles slower than active hourly scans.
- class PeriodMetrics
Bases:
objectTearsheet metrics for one period.
k_ratiousescalculate_k_ratio()with the 2013 scaling and 365 observations per year. Its wealth curve is the same daily share-price curve used for drawdown, including its first price and forward-filled days. It retains the adapter’s existing fee treatment without constructing a separate investor-net curve. Sparse prices make the score an approximation. Undefined scores remain null.flow_valueis the signed investor flow for the period: deposits minus redemptions. It is available from either separately observed flows or a state-based estimate. Stablecoin-denominated ERC-4626 vaults use an estimate derived from consecutive total-assets, total-supply and share-price snapshots. Shares minted as protocol fees are included in this state change because they cannot be distinguished from investor deposits without event-level data.deposit_value,redeem_value,deposit_countandredemption_countdescribe gross directional activity and are only available when individual deposit and redemption events have been extracted for the complete period. This is not currently supported for ERC-4626 vaults or most other protocols. These fields are never inferred by splitting the sign of a net state change.Monetary flow fields use the vault’s native denomination, including ETH or BTC where applicable. Flow fields in
periodic_metrics_usdcurrently remain null because historical conversion is not implemented. The current ERC-4626flow_valueestimate supports stablecoin-denominated vaults only. A day without an actual scanner observation makes the containing period unknown; a forward-filled state is never presented as zero flow.Lifetime flow values remain unset because the shared dataset does not carry flow-coverage boundaries from which a complete lifetime window could be established.
The deprecated top-level
netflowexport retains a directly calculated 1d value and compatibility aliases for the 7d and 30d period values.- period_start_at: Optional[pandas.Timestamp]
When was start share price sampled
- period_end_at: Optional[pandas.Timestamp]
When was end share price sampled
Share price at beginning
Share price at end
- annualisation_error_reason: Optional[str]
Why annualised returns are unavailable despite valid absolute returns.
- volatility: Optional[float]
Annualised volatility based on daily returns. For sparse price sources, missing days are forward filled and the result is an approximation.
- sharpe: Optional[float]
Sharpe ratio based on daily returns. For sparse price sources, missing days are forward filled and the result is an approximation. Eligible periods with no measurable return dispersion use the export value zero.
- k_ratio: Optional[float]
Kestner’s 2013 K-ratio of daily share prices, with 365 observations per year. Invalid or numerically log-linear curves have no defined score.
- ranking_curator: Optional[int]
Rank among vaults managed by the same curator (1 = best), based on CAGR
- avg_utilisation: Optional[float]
Average utilisation over the period (lending vaults only, 0.0–1.0)
- flow_value: Optional[float]
Signed flow value: deposits minus redemptions. For ERC-4626 this is estimated from total assets and total supply.
- deposit_value: Optional[float]
Gross deposited value, only when individual events were extracted. Always
Nonefor the current ERC-4626 state-based calculation.
- redeem_value: Optional[float]
Gross redeemed value, only when individual events were extracted. Always
Nonefor the current ERC-4626 state-based calculation.
- deposit_count: Optional[int]
Number of individually extracted deposit events during the period. Always
Nonefor the current ERC-4626 state-based calculation.
- redemption_count: Optional[int]
Number of individually extracted redemption events during the period. Always
Nonefor the current ERC-4626 state-based calculation.
- __init__(period, error_reason=None, period_start_at=None, period_end_at=None, share_price_start=None, share_price_end=None, raw_samples=0, samples_start_at=None, samples_end_at=None, daily_samples=0, returns_gross=None, returns_net=None, cagr_gross=None, cagr_net=None, annualisation_error_reason=None, volatility=None, sharpe=None, k_ratio=None, max_drawdown=None, tvl_start=None, tvl_end=None, tvl_low=None, tvl_high=None, ranking_overall=None, ranking_chain=None, ranking_protocol=None, ranking_curator=None, avg_utilisation=None, flow_value=None, deposit_value=None, redeem_value=None, deposit_count=None, redemption_count=None)
- Parameters
period (Literal['1W', '1M', '3M', '6M', '1Y', 'lifetime']) –
period_start_at (Optional[pandas.Timestamp]) –
period_end_at (Optional[pandas.Timestamp]) –
raw_samples (int) –
samples_start_at (Optional[pandas.Timestamp]) –
samples_end_at (Optional[pandas.Timestamp]) –
daily_samples (int) –
- Return type
None
- class USDPeriodMetrics
Bases:
eth_defi.research.vault_metrics.PeriodMetricsUSD-converted period metrics for one ETH/BTC vault period.
This JSON-only subtype leaves the public/native
PeriodMetricsschema untouched. The exchange-rate fields are USD per canonical underlying unit, e.g. Bitcoin price in US dollars for a BTC vault. Flow fields are currently unavailable for ETH/BTC vaults and remain null; they are not copied from or converted alongside the price and TVL fields.- __init__(period, error_reason=None, period_start_at=None, period_end_at=None, share_price_start=None, share_price_end=None, raw_samples=0, samples_start_at=None, samples_end_at=None, daily_samples=0, returns_gross=None, returns_net=None, cagr_gross=None, cagr_net=None, annualisation_error_reason=None, volatility=None, sharpe=None, k_ratio=None, max_drawdown=None, tvl_start=None, tvl_end=None, tvl_low=None, tvl_high=None, ranking_overall=None, ranking_chain=None, ranking_protocol=None, ranking_curator=None, avg_utilisation=None, flow_value=None, deposit_value=None, redeem_value=None, deposit_count=None, redemption_count=None, exchange_rate_start=None, exchange_rate_end=None)
- Parameters
period (Literal['1W', '1M', '3M', '6M', '1Y', 'lifetime']) –
period_start_at (Optional[pandas.Timestamp]) –
period_end_at (Optional[pandas.Timestamp]) –
raw_samples (int) –
samples_start_at (Optional[pandas.Timestamp]) –
samples_end_at (Optional[pandas.Timestamp]) –
daily_samples (int) –
- Return type
None
- USD_RATE_ERROR_MISSING_SERIES = 'USD exchange-rate series is unavailable'
USD metrics cannot be calculated because an ETH/BTC rate series is absent.
- USD_RATE_ERROR_INVALID_SERIES = 'USD exchange-rate series failed validation'
USD metrics cannot be calculated because an ETH/BTC rate series failed validation.
- USD_RATE_ERROR_INSUFFICIENT_COVERAGE = 'USD exchange-rate coverage is insufficient'
USD metrics cannot be calculated without a contiguous bounded rate window.
- class CryptoUSDConversionContext
Bases:
objectCleaned ETH/BTC USD-rate inputs for one crypto metadata build.
The context is optional in the common metrics pipeline. Public stablecoin callers keep their existing behaviour by passing
None. Values are keyed by denomination family strings ("eth"and"btc"), while the vault mapping is built by the crypto bundle before JSON-only canonical-underlying fields exist.- rates_by_family: collections.abc.Mapping[str, pandas.Series]
Bounded effective-date USD-per-underlying daily rates by family.
- errors_by_family: collections.abc.Mapping[str, str]
Family-specific validation or absence errors by family.
- vault_families: collections.abc.Mapping[str, str]
Vault ID to denomination family mapping from crypto metadata policy.
- __init__(rates_by_family, errors_by_family, vault_families)
- Parameters
rates_by_family (collections.abc.Mapping[str, pandas.Series]) –
errors_by_family (collections.abc.Mapping[str, str]) –
vault_families (collections.abc.Mapping[str, str]) –
- Return type
None
- class NetflowMetrics
Bases:
objectDeprecated legacy top-level deposit and withdrawal flow metrics.
Deprecated: Do not use this dataclass in new integrations. Use
PeriodMetricsand itsflow_valuefield instead. Gross directional values and counts remain available there only when individual events were extracted.The top-level
netflowexport retains this type only for backwards compatibility; its 7d and 30d values are aliases filled from the1Wand1MPeriodMetricsresults respectively.The 1d legacy entry remains calculated directly because there is no matching performance period. Despite their historical
*_usdnames, monetary fields use the same native denomination asPeriodMetrics. Flow fields inperiodic_metrics_usdcurrently remain null.data_completecertifies signed net-flow coverage; gross legacy fields can still be null when individual events were not extracted.- withdrawal_usd: Optional[float]
Legacy gross withdrawal value, only from individually extracted events.
- __init__(period, deposit_count=None, withdrawal_count=None, deposit_usd=None, withdrawal_usd=None, net_flow_usd=None, data_complete=False)
- LOOKBACK_AND_TOLERANCES: dict[Literal['1W', '1M', '3M', '6M', '1Y', 'lifetime'], tuple[pandas.DateOffset, pandas.Timedelta]] = {'1M': (<DateOffset: days=30>, Timedelta('60 days 00:00:00')), '1W': (<DateOffset: days=7>, Timedelta('12 days 00:00:00')), '1Y': (<DateOffset: days=365>, Timedelta('410 days 00:00:00')), '3M': (<DateOffset: days=90>, Timedelta('135 days 00:00:00')), '6M': (<DateOffset: days=180>, Timedelta('225 days 00:00:00')), 'lifetime': (<DateOffset: years=100>, Timedelta('36500 days 00:00:00'))}
Period -> period duration, max sparse sample mismatch
- class VaultWhitelist
Bases:
TypedDictVault-wide KYC status and its qualification notes.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- class VaultMetricsRecord
Bases:
TypedDictPer-vault record in the JSON export.
Uses
total=Falseso that only the most critical fields are typed explicitly — remaining fields are still present but not enforced by the type checker. This is an incremental approach; more fields can be promoted to required as the schema stabilises.- deployment: Optional[str]
Native protocol deployment slug, or
Nonefor ordinary EVM vaults.For now this is populated for Lighter so consumers can distinguish the original
ethereumdeployment from Lighter onrobinhoodwhile retaining Lighter’s synthetic vault-dataset chain ID.
- deployment_chain_id: Optional[int]
Real EVM chain ID associated with a native protocol deployment.
For now this is populated for Lighter on Ethereum (1) and Lighter on Robinhood Chain (4663). Both deployments keep
chain_id=9998because they share the native Lighter dataset namespace; their synthetic address prefixes and these deployment fields distinguish individual vaults.
- strategy_tags: Optional[list[str]]
Maintained investment strategy classifications, or
Nonewhen the strategy information is missing.
- vault_poll_frequency: Optional[str]
Latest adaptive vault scan cycle, e.g.
"large_tvl"or"peaked".
Source used to produce the share-price series.
Current net asset value in USD
Peak net asset value in USD
- denomination_decimals: Optional[int]
Denomination (reserve) token ERC-20 decimals, e.g.
6for USDC. Consumers use this to convert human amounts to raw uint256; a missing value must NOT be defaulted to 18 (seedenomination_token_address).
- minimum_deposit: Optional[float]
Minimum deposit in decimal denomination-token units.
0means the scanner verified that this vault has no minimum.Nonemeans the value is unavailable; it must not be interpreted as a zero minimum.
- minimum_redemption: Optional[float]
Minimum redemption in decimal vault-share units.
0means the scanner verified that this vault has no minimum.Nonemeans the value is unavailable; it must not be interpreted as a zero minimum.
- deposit_manager: Optional[dict]
Static support for this library’s deposit/redemption manager, or
None.This does not mean the vault is currently open or that an account has permission, funds, acceptable slippage, spare cap, or liquidity.
- deposit_permission: str
Vault-wide account-admission policy.
whitelistednormally means deposits require prior KYC, manual identity approval, or a source-proven recipient allowlist.permissionlessmeans no prior account approval applies andunknownmeans the scanner has no source-proven result for this contract version. Open dates, lock-ups, epoch windows, pauses, caps and token-holding requirements do not change this status. Consultwhitelist.notesfor protocol-specific qualifications. Native perp DEX vaults use a documented compatibility exception where closed public participation maps towhitelistedwith a mandatory qualification note.
- whitelist: eth_defi.research.vault_metrics.VaultWhitelist
Structured vault-wide account-admission status.
statusmirrorsdeposit_permission.notescontains a protocol-specific qualification where the scanner must expose one.
Share token ERC-20 decimals (the vault’s own ERC-4626 token).
- core3: Optional[eth_defi.core3.vault_protocol.Core3VaultSection]
Compact Core3 risk summary for the vault’s protocol, or
Nonewhen no Core3 data is available. SeeCore3VaultSection.
- xerberus: Optional[eth_defi.xerberus.vault_export.XerberusVaultSection]
Compact Xerberus risk summary for this vault (pool score preferred), or
Nonewhen no Xerberus data is available. Unlikecore3, this is primarily a per-vault rating when the pool is scored. SeeXerberusVaultSection.
- denomination_token_rate: eth_defi.feed.stablecoin_rate.DenominationTokenRate
Stablecoin rate data for the vault denomination token.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- class ExportVersionMetadata
Bases:
TypedDictGit version stamp of the exporter Docker image.
Produced by
eth_defi.version_info.VersionInfo.as_dict(). All fields areNonewhen the exporter runs outside a stamped Docker image, e.g. from a source checkout. Individual fields can also beNoneinside a stamped image when the corresponding build ARG was not passed.- tag: Optional[str]
Git tag at image build time, e.g.
v0.30.Often
None: only set when the image was built from a tagged commit with theGIT_VERSION_TAGbuild ARG. Consumers should rely oncommit_hashas the primary build identifier.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- class ExportMetadata
Bases:
TypedDictProvenance metadata for the vault metrics JSON export.
Identifies which exporter build produced the file so stale deployments are diagnosable from the JSON alone.
- version: eth_defi.research.vault_metrics.ExportVersionMetadata
Git version stamp of the exporter Docker image.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- class VaultMetricsExport
Bases:
TypedDictTop-level structure of the vault metrics JSON export.
Describes the shape of
top_vaults_by_chain.jsonuploaded to R2.- metadata: eth_defi.research.vault_metrics.ExportMetadata
Export provenance metadata, see
ExportMetadata.
- core3_protocols: dict[str, eth_defi.core3.vault_protocol.Core3ExportRecord]
Core3 risk intelligence keyed by protocol slug. Only protocols present in the exported vaults are included.
- xerberus_protocols: dict[str, eth_defi.xerberus.vault_export.XerberusProtocolExportRecord]
Xerberus protocol-level metadata keyed by our protocol slug. Only protocols present in the exported vaults are included. Per-vault scores live on each vault row under
xerberus.
- curators: dict[str, 'CuratorExportRecord']
Curator metadata and recent feed entries keyed by curator slug. Only curators present in the exported vaults are included.
- categories: NotRequired[dict[str, 'StrategyCategoryExportRecord']]
Strategy category labels, rules, and aggregates keyed by strategy tag.
Omitted only when best-effort category aggregation fails. The rest of the public vault export remains valid and publishable in that case.
- vaults: list[eth_defi.research.vault_metrics.VaultMetricsRecord]
List of per-vault metric records
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- class StrategyCategoryExportRecord
Bases:
TypedDictOne public strategy category and its aggregate vault metrics.
- vault_count: int
Number of eligible exported vaults carrying this category tag. Excludes blacklisted or stale rows and rows with missing, invalid, or broken current TVL.
- one_month_apy: Optional[float]
Current-TVL-weighted annualised one-month return, or
Nonewhen no eligible tagged vault has both valid current USD TVL and a complete, bounded 1M return observation covering at least 28 days. Net return is preferred when known.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- clear()
Remove all items from the dict.
- copy()
Return a shallow copy of the dict.
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items()
Return a set-like object providing a view on the dict’s items.
- keys()
Return a set-like object providing a view on the dict’s keys.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values()
Return an object providing a view on the dict’s values.
- make_vault_display_flags(red_flags, yellow_flags, source)
Build generic vault warning display entries for JSON export.
- Parameters
- Returns
JSON-safe warning entries suitable for user interfaces.
- Return type
- fmt_one_decimal_or_int(x)
Display fees to .1 accuracy if there are .1 fractions, otherwise as int.
- slugify_protocol(protocol)
Create a slug from protocol name for URLs.
- slugify_vault(name, symbol, address, existing_slugs)
Create a slug from vault metadata for URLs.
- create_fee_label(fee_data)
Create 2% / 20% style labels to display variosu kinds of vault fees.
Order is: management / performance / deposit / withdrawal fees.
- Parameters
fee_data (eth_defi.vault.fee.FeeData) –
- resample_returns(returns_1h, freq='D')
Calculate regular period returns from a finer-grained return series.
Empty output periods carry the last wealth value and therefore produce a zero return. Any accumulated movement appears in the next observed period. This forward-fill convention is an accepted approximation for sparse sources and guarantees one value per consecutive period. Risk metrics calculated from the result remain sensitive to observation cadence.
- Parameters
returns_1h (pandas.Series) – The original returns series.
freq – Pandas resampling frequency. Defaults to daily.
- Returns
Regular period percentage returns.
- Return type
- calculate_returns(share_price, freq='D')
Calculate regular period returns from share-price observations.
Missing output periods are forward filled before percentage changes are calculated. An unobserved period therefore receives a zero return and the full accumulated movement appears in the next observed period. This is an accepted approximation for sparse sources: it provides consecutive inputs for common risk metrics, but those metrics remain sensitive to observation cadence.
- Parameters
share_price (pandas.Series) – Share-price observations with a
pandas.DatetimeIndex.freq – Pandas resampling frequency. Defaults to daily.
- Returns
Regular period percentage returns.
- Return type
- calculate_cumulative_returns(cleaned_returns, freq='D')
Takes a returns series and calculates cumulative returns.
The cleaned returns series is created by
eth_defi.research.wrangle_vault_prices.
- Parameters
cleaned_returns (pandas.Series) –
- zero_out_near_zero_prices(s, eps=1e-09, clip_negatives=True)
Replace values with abs(x) < eps by 0. Optionally clip negatives to 0.
Keeps NaN as-is, turns +/- inf into NaN.
- Parameters
s (pandas.Series) –
eps (float) –
clip_negatives (bool) –
- Return type
- calculate_net_profit(start, end, share_price_start, share_price_end, management_fee_annual, performance_fee, deposit_fee, withdrawal_fee, seconds_in_year=31557600.0, sample_count=None)
Calculate profit after external fees have been reduced from the share price change.
- Parameters
start (datetime.datetime) – Start datetime of the investment period.
end (datetime.datetime) – End datetime of the investment period.
share_price_start (float) – Share price at the start of the investment period.
share_price_end (float) – Share price at the end of the investment period.
management_fee_annual (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Annual management fee as a percent (0.02 = 2% per year).
performance_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Performance fee as a percent (0.20 = 20% of profits).
deposit_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Deposit fee as a percent (0.01 = 1% fee), or None if no fee.
withdrawal_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Withdrawal fee as a percent (0.01 = 1% fee), or None if no fee.
sample_count (Optional[int]) – If we have not enough returns data, do not try to calculate profit.
- Returns
Net profit as a floating point (0.10 = 10% profit).
- Return type
- calculate_net_returns_from_price(name, share_price, management_fee_annual, performance_fee, deposit_fee, withdrawal_fee, seconds_in_year=31557600.0, zero_epsilon=0.001, freq='h')
Convert a share price series to net return series after fees.
- Parameters
name (str) – For debugging
share_price (pandas.Series) – Share price series with datetime index.
management_fee_annual (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Annual management fee as a percent (0.02 = 2% per year).
performance_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Performance fee as a percent (0.20 = 20% of profits).
deposit_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Deposit fee as a percent (0.01 = 1% fee), or None if no fee.
withdrawal_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Withdrawal fee as a percent (0.01 = 1% fee), or None if no fee.
freq – The time series frequency (hourly, daily, etc) for management fee calculation.
- Returns
Cumulative net profit as a floating point (0.10 = 10% profit).
- Return type
- calculate_net_returns_from_gross(name, cumulative_returns, management_fee_annual, performance_fee, deposit_fee, withdrawal_fee, seconds_in_year=31557600.0)
Convert a cumulative gross return series to a cumulative net return series after fees.
This function correctly models a High-Water Mark (HWM) for performance fees, which requires an iterative calculation (a loop). This loop operates on Numpy arrays for maximum speed.
Management fees are accrued based on the time delta of each period.
Performance fees are charged only on profits above the highest net value.
Deposit fees are applied once at the start (t=0).
Withdrawal fees are applied once at the end (t=T).
- Parameters
name (str) – Name for the returned pandas Series.
cumulative_returns (pandas.Series) – A pandas Series with a DatetimeIndex representing the cumulative gross return index (e.g., 1.0, 1.02, 1.05) OR cumulative gross profit (e.g., 0.0, 0.02, 0.05).
management_fee_annual (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Annual management fee as a decimal (e.g., 0.02 for 2%).
performance_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Performance fee as a decimal (e.g., 0.20 for 20% of profits above the High-Water Mark).
deposit_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Fee applied to the initial deposit as a decimal (e.g., 0.01 for 1%).
withdrawal_fee (Optional[Union[float, decimal.Decimal, Literal['-']]]) – Fee applied to the final withdrawal as a decimal (e.g., 0.01 for 1%).
seconds_in_year – The number of seconds in a year for precise management fee accrual.
- Returns
A pandas Series of the cumulative net profit (e.g., 0.10 for 10%).
- Return type
Create one regular daily price and return series from sparse observations.
Vault prices may be persisted only when a configured change threshold is exceeded. Some sources, including GMX, also produce valuations only when a protocol operation emits an event. Missing calendar days are forward filled with the last known price before daily returns are calculated.
Forward filling is an accepted approximation for these sparse sources. It assigns a zero return to each unobserved day and the full intervening price movement to the next observed day. This creates a common daily input for volatility, Sharpe and drawdown calculations, but the path-dependent results are sensitive to event cadence and are not continuous NAV metrics.
Build this pair once per vault and pass it to every period calculation.
This pandas entry point shares its calculation with the array path used by
calculate_lifetime_metrics(), see_prepare_daily_share_price_arrays(), so both produce the same curve.- Parameters
share_price_observations (pandas.Series) – Sparse share-price observations with a naive UTC
pandas.DatetimeIndex. Values must be decimal share-price levels, not returns.- Returns
Approximate regular daily share prices and their daily percentage returns, indexed by calendar day with
freq="D". The first return isNaNbecause no preceding daily price exists.- Return type
- calculate_annualised_volatility_from_daily_returns(daily_returns, annualisation_factor=365)
Calculate annualised volatility from regular daily returns.
- Parameters
daily_returns (pandas.Series) – Percentage returns with exactly one observation per consecutive calendar day. Call
prepare_daily_share_price_series()first when the source price observations are sparse.annualisation_factor (float) – Calendar periods per year. Crypto vaults use 365 daily periods.
- Returns
Annualised standard deviation, or zero with fewer than two usable returns or a non-finite result. For a forward-filled sparse source, this is an observation-cadence-sensitive approximation.
- Return type
- calculate_sharpe_ratio_from_returns(daily_returns, risk_free_rate=0.0, annualisation_factor=365, sample_duration=None)
Calculate annualised Sharpe ratio from regular daily returns.
Sparse change-only observations must be converted to one price per consecutive calendar day and forward filled before calculating the input returns. This accepted approximation treats an unobserved day as flat and assigns the accumulated movement to the next observed day. Use
prepare_daily_share_price_series()for vault data. The resulting Sharpe ratio is therefore sensitive to observation cadence and must not be interpreted as a continuously sampled NAV statistic.- Parameters
daily_returns (pandas.Series) – Percentage returns with exactly one observation per consecutive calendar day.
risk_free_rate (float) – Annualised risk-free rate. Defaults to zero.
annualisation_factor (float) – Calendar periods per year. Crypto vaults use 365 daily periods.
sample_duration (Optional[pandas.Timedelta]) – Calendar duration covered by the return series. When supplied, it must meet
MINIMUM_SHARPE_SAMPLE_DURATION.
- Returns
Annualised Sharpe ratio, or
Nonewhen the available history cannot support the ranking statistic.- Return type
- slugify_vaults(vaults)
Create slugs for a set of vaults.
Always give the primary slug to the vault that was created first.
Mutates VaultRow data in-place
- Parameters
vaults (dict[eth_defi.vault.base.VaultSpec, eth_defi.vault.vaultdb.VaultRow]) – The vault metadata entries.
- Return type
- FLOW_AMOUNT_COLUMNS: tuple[str, str] = ('daily_deposit_usd', 'daily_withdrawal_usd')
Daily directional-flow columns supplied by protocol data sources.
- FLOW_VALUE_COLUMN: str = 'daily_flow_value'
Daily signed flow used when gross directional events are unavailable.
- FLOW_COUNT_COLUMNS: tuple[str, str] = ('daily_deposit_count', 'daily_withdrawal_count')
Daily event-count columns required before gross flows may be published.
- ERC4626_FLOW_STATE_COLUMNS: tuple[str, str, str] = ('total_assets', 'total_supply', 'share_price')
Vault accounting columns required for an ERC-4626 flow estimate.
- MAX_ERC4626_FLOW_STATE_RESIDUAL: float = 0.001
Maximum relative divergence between total assets and supply times share price.
- VAULT_STATE_OBSERVED_COLUMN = '_vault_state_observed'
Whether a regular daily row contains one fresh, complete vault state.
- NANOSECONDS_PER_DAY = 86400000000000
Nanoseconds in one calendar day, the unit of the integer timestamps below.
The metric helpers work on
int64nanosecond timestamps, because integer comparison andnumpy.searchsorted()are far cheaper than pandas label lookups on apandas.DatetimeIndex. Integer division by this constant gives the UTC calendar day of a naive UTC timestamp.
- calculate_period_metrics(period, gross_fee_data, net_fee_data, share_price_hourly, share_price_daily, daily_returns, tvl, now_, utilisation=None, native_fee_share_price=None, exchange_rate=None)
Calculate metrics for one period.
This pandas entry point converts its inputs with
_period_inputs_from_series()and delegates to_calculate_period_metrics_from_arrays(). Batch calculations should convert once per vault and callcalculate_period_results()instead.K-ratio uses the 2013 convention on the supplied daily price curve, with 365 observations per year and no additional fee adjustment. See
calculate_k_ratio()andPeriodMetrics.- Parameters
period (Literal['1W', '1M', '3M', '6M', '1Y', 'lifetime']) – Period identifier (1W, 1M, 3M, 6M, 1Y, lifetime)
gross_fee_data (eth_defi.vault.fee.FeeData) – Fee data before fee mode adjustments
net_fee_data (eth_defi.vault.fee.FeeData) – Fee data after fee mode adjustments (for net return calculations)
share_price_hourly (pandas.Series) – Sparse source share-price observations with a DatetimeIndex. The historical name is retained for API compatibility; the series is not assumed to contain every hour.
share_price_daily (pandas.Series) – Regular, forward-filled daily share-price series prepared once for the vault with
prepare_daily_share_price_series(). For sparse sources, this is an explicit approximation rather than a continuous NAV series.daily_returns (pandas.Series) – Regular daily returns derived once from
share_price_daily. The same series must be passed to every period calculation for the vault. Unobserved days have zero return and the next observed day receives the accumulated movement.tvl (pandas.Series) – Total value locked series with DatetimeIndex
now – The reference timestamp (usually the last timestamp in the data)
utilisation (Optional[pandas.Series]) – Optional regular daily utilisation series (lending vaults only, values 0.0–1.0). When provided,
avg_utilisationis a calendar-day average for the period rather than an observation-frequency average.native_fee_share_price (Optional[pandas.Series]) – Optional sparse native-denomination prices aligned to
share_price_hourly. USD metrics use these values when calculating externalised investor fees, so a vault performance fee is never charged on ETH/BTC/USD market appreciation.exchange_rate (Optional[pandas.Series]) – Optional USD-per-underlying sparse rate series aligned to
share_price_hourly. Must be supplied together withnative_fee_share_price.now_ (pandas.Timestamp) –
- Returns
PeriodMetrics dataclass with calculated metrics
- Return type
- calculate_period_results(*, gross_fee_data, net_fee_data, share_price_observations, share_price_daily, daily_returns, tvl, now_, utilisation=None, native_fee_share_price=None, exchange_rate=None)
Calculate every established period from paired sparse and daily inputs.
The sparse observations preserve the established endpoint, raw-sample and fee semantics. The daily curve is independently supplied for volatility, Sharpe, K-ratio and drawdown. USD metrics reuse this helper with native fee-basis prices and matching USD-per-underlying rates.
The pandas inputs are converted to arrays once and shared by all six periods; see
_calculate_period_metrics_from_arrays().- Parameters
gross_fee_data (eth_defi.vault.fee.FeeData) – Vault fee schedule before fee-mode adjustments.
net_fee_data (eth_defi.vault.fee.FeeData) – Investor-facing fee schedule after fee-mode adjustments.
share_price_observations (pandas.Series) – Sparse real price observations used for period endpoints.
share_price_daily (pandas.Series) – Regular covered daily price curve used for risk metrics.
daily_returns (pandas.Series) – Daily returns derived from
share_price_daily.tvl (pandas.Series) – TVL curve aligned to the selected metric view.
now – Last timestamp of the selected contiguous metric segment.
utilisation (Optional[pandas.Series]) – Optional regular daily utilisation curve.
native_fee_share_price (Optional[pandas.Series]) – Optional native sparse fee-basis prices for a converted USD view.
exchange_rate (Optional[pandas.Series]) – Optional sparse USD-per-underlying rates for a converted USD view.
now_ (pandas.Timestamp) –
- Returns
One
PeriodMetricsinstance for each established lookback.- Return type
- calculate_crypto_usd_period_results(*, context, vault_id, native_share_price_observations, native_daily_share_prices, native_total_assets, gross_fee_data, net_fee_data)
Calculate JSON-only USD period metrics for an ETH/BTC crypto vault.
A provider-rate gap longer than the configured bounded fill creates a new segment. This function uses only the latest contiguous covered segment and filters sparse real vault observations to it before calculating endpoints or fees. Stablecoin vaults return
Noneand retain their native metrics.- Parameters
context (eth_defi.research.vault_metrics.CryptoUSDConversionContext) – Prepared crypto conversion rates and vault denomination mapping.
vault_id (str) – Common
chain-addressvault identifier.native_share_price_observations (pandas.Series) – Sparse real native share-price observations.
native_daily_share_prices (pandas.Series) – Existing forward-filled native daily share-price curve.
native_total_assets (pandas.Series) – Sparse native total-assets observations.
gross_fee_data (eth_defi.vault.fee.FeeData) – Vault fee schedule before fee-mode adjustments.
net_fee_data (eth_defi.vault.fee.FeeData) – Investor-facing fee schedule after fee-mode adjustments.
- Returns
USD period metrics for ETH/BTC with USD-per-underlying endpoint rates, an errored list when rate input is unavailable, or
Nonefor non-crypto-denominated records.- Return type
Optional[list[eth_defi.research.vault_metrics.USDPeriodMetrics]]
- apply_abnormal_value_checks(risk, notes, flags, current_nav=None, current_share_price=None, three_months_volatility=None)
Check for broken vaults by detecting abnormal metric values.
Automatically blacklists vaults with unrealistic TVL, share price, or volatility. These thresholds catch broken smart contracts and low-TVL vaults that produce meaningless metrics.
Called multiple times as more metrics become available (first with NAV/price, then again after 3M volatility is computed).
- Parameters
risk (eth_defi.vault.risk.VaultTechnicalRisk) – Current risk classification.
notes (str) – Current notes string.
flags (set[eth_defi.vault.flag.VaultFlag]) – Current vault flags set.
current_nav (Optional[float]) – Current TVL in USD. Checked against
MAX_VALID_NAV.current_share_price (Optional[float]) – Current share price. Checked against
MAX_VALID_SHARE_PRICE.three_months_volatility (Optional[float]) – 3-month annualised volatility. Checked against
MAX_VALID_VOLATILITY. Catches low-TVL Hyperliquid vaults with one or few trades that produce extreme volatility numbers.
- Returns
Updated (risk, notes, flags) tuple.
- Return type
tuple[eth_defi.vault.risk.VaultTechnicalRisk, str, set[eth_defi.vault.flag.VaultFlag]]
- apply_morpho_not_in_api_check(risk, notes, flags)
Blacklist Morpho vaults missing from Morpho API.
Dynamic scan flags are not visible to
get_vault_risk(), because that helper only reads the static manual flag table. This helper handles the Morpho-specific dynamic blacklist flag before metrics export.- Parameters
risk (Optional[eth_defi.vault.risk.VaultTechnicalRisk]) – Current risk classification.
notes (Optional[str]) – Current note, if any. Existing notes have priority.
flags (set[eth_defi.vault.flag.VaultFlag]) – Dynamic flags collected during vault scan.
- Returns
Updated risk, notes, and flags.
- Return type
tuple[eth_defi.vault.risk.VaultTechnicalRisk | None, str | None, set[eth_defi.vault.flag.VaultFlag]]
- apply_bad_flag_check(risk, notes, flags)
Blacklist vaults that carry scanned bad flags.
Scan-time flags may come from protocol adapters and are not visible to
get_vault_risk(), which only checks the static manual flag table. Any flag listed ineth_defi.vault.flag.BAD_FLAGSmeans the vault must not be exported as a normal investable row.- Parameters
risk (Optional[eth_defi.vault.risk.VaultTechnicalRisk]) – Current risk classification.
notes (Optional[str]) – Current note, if any. Existing notes are preserved.
flags (set[eth_defi.vault.flag.VaultFlag]) – Scan-time and manual flags collected for the vault.
- Returns
Updated risk, notes, and flags.
- Return type
tuple[eth_defi.vault.risk.VaultTechnicalRisk | None, str | None, set[eth_defi.vault.flag.VaultFlag]]
- format_bad_flag_note(bad_flags)
Create a generic note for vaults that carry bad scan flags.
This note is used before any protocol-specific metadata has been analysed. Later checks may replace it with a richer note if the generic bad flag and the protocol-specific warning describe the same underlying issue.
- Parameters
bad_flags (set[eth_defi.vault.flag.VaultFlag]) – Bad vault flags to report.
- Returns
Human-readable note.
- Return type
- normalise_vault_poll_frequency(value)
Normalise a raw vault scan cycle value.
The cleaned price parquet may carry missing values as
None,NaNorpd.NAdepending on how the column was materialised. This helper converts valid scan cycle values to stripped strings and hides missing values from JSON-facing metric records.
- get_latest_vault_poll_frequency(prices_df)
Get the latest known vault scan cycle from price rows.
vault_poll_frequencyis produced during the vault scan and persisted in cleaned price data. Some historical rows may be empty, so this helper walks the values backwards and returns the newest non-empty scan cycle.- Parameters
prices_df (pandas.DataFrame) – Price DataFrame for one vault, conforming to
CleanedVaultPriceRow.- Returns
Latest scan cycle string, or
Noneif the column is not available.- Return type
- extend_notes_with_vault_scan_cycle(notes, vault_poll_frequency)
Append lower scan-cycle context to a vault note.
Frontends use the note field as the short human explanation for unusual vault state. When a vault is intentionally scanned less often, this helper adds that explanation without replacing existing risk or manual notes.
- METRIC_ARRAY_COLUMNS: tuple[str, ...] = ('share_price', 'total_assets', 'total_supply', 'utilisation', 'daily_deposit_usd', 'daily_withdrawal_usd', 'daily_deposit_count', 'daily_withdrawal_count', 'daily_flow_value')
Numeric price columns that the metric calculations read as arrays.
Everything else a record needs from the price rows is a single exported scalar, such as the latest block number. Those scalars are read directly from the source frame so they keep their original Python or NumPy type.
- calculate_vault_record(prices_df, vault_metadata_rows, vault_id=None, core3_protocols=None, xerberus_pools=None, xerberus_protocols=None, stablecoin_rate_feeder=None, crypto_usd_conversion_context=None, *, price_observations=None)
Process a single vault metadata + prices to calculate its full data.
Single-vault DataFrame entry point. It converts the frame with
_prepare_vault_price_frame()and calls_calculate_vault_record_from_arrays(), the implementation thatcalculate_lifetime_metrics()uses for every vault. Batch callers should usecalculate_lifetime_metrics(), which converts the whole multi-vault frame once instead of once per vault.- Parameters
prices_df (pandas.DataFrame) – Price DataFrame for a single vault, conforming to
CleanedVaultPriceRow. ERC-4626 flow estimation requires the consecutive daily frame produced bycalculate_hourly_returns_for_all_vaults(); other callers retain null flow fields and log the reason.vault_id (Optional[str]) – Vault ID string. If not provided, extracted from prices_df[“id”].
price_observations (Optional[pandas.DataFrame]) – Optional single-vault observations before daily aggregation, indexed by naive UTC time, with
share_price,total_assetsandblock_numbercolumns. Used for return endpoints and sample counts.vault_metadata_rows (dict[eth_defi.vault.base.VaultSpec, eth_defi.vault.vaultdb.VaultRow]) –
core3_protocols (Optional[dict[str, eth_defi.core3.vault_protocol.Core3ExportRecord]]) –
xerberus_pools (Optional[dict[tuple[int, str], eth_defi.xerberus.vault_export.XerberusPoolLookupRow]]) –
xerberus_protocols (Optional[dict[str, eth_defi.xerberus.vault_export.XerberusProtocolExportRecord]]) –
stablecoin_rate_feeder (Optional[eth_defi.feed.stablecoin_rate.StablecoinRateFeeder]) –
crypto_usd_conversion_context (Optional[eth_defi.research.vault_metrics.CryptoUSDConversionContext]) –
- Return type
See
_calculate_vault_record_from_arrays()for the other parameters.- Returns
Series with calculated metrics
- Parameters
prices_df (pandas.DataFrame) –
vault_metadata_rows (dict[eth_defi.vault.base.VaultSpec, eth_defi.vault.vaultdb.VaultRow]) –
core3_protocols (Optional[dict[str, eth_defi.core3.vault_protocol.Core3ExportRecord]]) –
xerberus_pools (Optional[dict[tuple[int, str], eth_defi.xerberus.vault_export.XerberusPoolLookupRow]]) –
xerberus_protocols (Optional[dict[str, eth_defi.xerberus.vault_export.XerberusProtocolExportRecord]]) –
stablecoin_rate_feeder (Optional[eth_defi.feed.stablecoin_rate.StablecoinRateFeeder]) –
crypto_usd_conversion_context (Optional[eth_defi.research.vault_metrics.CryptoUSDConversionContext]) –
price_observations (Optional[pandas.DataFrame]) –
- Return type
- calculate_lifetime_metrics(df, vault_db, returns_column='returns_1h', core3_protocols=None, xerberus_pools=None, xerberus_protocols=None, stablecoin_rate_feeder=None, crypto_usd_conversion_context=None, *, price_observations=None)
Calculate lifetime metrics for each vault in the provided DataFrame.
All-time returns
3M returns, latest
1M returns, latest
Volatility (3M)
Lookback based on the last entry.
Every
period_resultsentry includesk_ratio, calculated with the 2013 formula on forward-filled daily share prices at 365 observations per year. It follows the existing price basis rather than estimating a separate net wealth curve; undefined values areNone. The same calculation uses USD-converted daily prices inperiodic_metrics_usd, when available.Performance: the frame’s metric columns are converted to NumPy once (
_prepare_vault_price_frame()), and each vault is then a set of array slices instead of a pandas group. On the 2026-09-25 production snapshot of 12,795 stablecoin vaults, this took 22.8 s, compared with 235 s for a pandas group per vault, with identical exported rows. Most of that time had gone into pandas overhead on small per-vault frames, not into the metric arithmetic.Each output row contains a
share_price_sourcestring describing how the adapter obtained its share-price observations, orNonefor legacy metadata and adapters without a price source.Each output row also contains a
denomination_token_ratevalue produced byeth_defi.feed.stablecoin_rate.StablecoinRateFeeder.get_denomination_token_rate_section(). The value is aeth_defi.feed.stablecoin_rate.DenominationTokenRatecarrying both USD rate fields and, for non-USD stablecoins, native source currency rate fields.Each output row exports
minimum_depositin denomination-token units andminimum_redemptionin vault-share units.Nonemeans the scanner did not establish the relevant protocol limit, while0means it established that the vault has no minimum for that action.- Parameters
df (pandas.DataFrame) – Cleaned price DataFrame conforming to
CleanedVaultPriceRow. Must have aDatetimeIndex. ERC-4626 flow estimation additionally requires the consecutive daily frame produced bycalculate_hourly_returns_for_all_vaults(); otherwise the flow fields remain null and the reason is logged.vault_db (Union[eth_defi.vault.vaultdb.VaultDatabase, dict[eth_defi.vault.base.VaultSpec, eth_defi.vault.vaultdb.VaultRow]]) – Pass all vaults or subset of vaults as VaultRows, or full VaultDatabase
core3_protocols (Optional[dict[str, eth_defi.core3.vault_protocol.Core3ExportRecord]]) – Optional Core3 risk records keyed by our protocol slug, as returned by
eth_defi.core3.vault_protocol.build_core3_protocols_for_export(). Threaded through tocalculate_vault_record()to attach a per-vaultcore3summary.Noneto skip Core3 enrichment.xerberus_pools (Optional[dict[tuple[int, str], eth_defi.xerberus.vault_export.XerberusPoolLookupRow]]) – Optional preloaded Xerberus pool lookup for per-vault scores.
Noneto skip pool-level Xerberus enrichment.xerberus_protocols (Optional[dict[str, eth_defi.xerberus.vault_export.XerberusProtocolExportRecord]]) – Optional Xerberus protocol map for fallback scores and context.
Noneto skip protocol-level Xerberus enrichment.stablecoin_rate_feeder (Optional[eth_defi.feed.stablecoin_rate.StablecoinRateFeeder]) – Stablecoin rate/depeg lookup helper shared across all vault rows in this calculation. If omitted, one default feeder is constructed.
crypto_usd_conversion_context (Optional[eth_defi.research.vault_metrics.CryptoUSDConversionContext]) – Optional USD conversion context for the crypto bundle. ETH/BTC output records contain an additional
periodic_metrics_usdfield when it is supplied; all existing native metrics preserve their semantics.price_observations (Optional[pandas.DataFrame]) – Optional source observations before daily aggregation, indexed by naive UTC timestamps with
id,share_price,total_assetsandblock_numbercolumns. Returns retain their real first and last observations whiledfsupplies daily states and flows.returns_column (str) –
- Returns
DataFrame, one row per vault.
- Return type
- get_period_metrics(period_results, period)
Get PeriodMetrics for a specific period from the results list.
- Parameters
period_results (list[eth_defi.research.vault_metrics.PeriodMetrics]) – List of PeriodMetrics objects from a vault record
period (Literal['1W', '1M', '3M', '6M', '1Y', 'lifetime']) – The period to find (e.g., “1W”, “1M”, “3M”, “6M”, “1Y”, “lifetime”)
- Returns
The matching PeriodMetrics or None if not found
- Return type
- calculate_vault_rankings(results_df, min_tvl_chain_protocol=10000, min_tvl_overall=50000, min_tvl_curator=100)
Calculate rankings for all periods inside PeriodMetrics objects.
Updates PeriodMetrics objects in-place within the period_results lists. Rankings are calculated for all 6 periods (1W, 1M, 3M, 6M, 1Y, lifetime).
Vaults are excluded from rankings if: - They have no CAGR data (zero or NaN) - They have an error_reason set - They are blacklisted (risk == VaultTechnicalRisk.blacklisted) - They are disabled GMX products retained only for historical continuity - Their period TVL is below the applicable ranking threshold
- Parameters
results_df (pandas.DataFrame) – DataFrame from calculate_lifetime_metrics()
min_tvl_chain_protocol (float) – Minimum TVL required for chain and protocol rankings (default: $10,000)
min_tvl_overall (float) – Minimum TVL required for overall rankings (default: $50,000)
min_tvl_curator (float) – Minimum TVL required for curator rankings (default: $100)
- Returns
DataFrame with rankings updated in PeriodMetrics objects
- Return type
- SPECIAL_VAULT_PROTOCOL_SLUGS = {'derive', 'grvt', 'hibachi', 'hyperliquid', 'lighter'}
Protocol slugs for vaults where we do not necessarily have on-chain deposit/redeem event data.
These vaults get their data from off-chain APIs (e.g. GRVT, Hyperliquid, Lighter) or are hardcoded protocol entries that may lack standard ERC-4626 events.
- is_special_vault(protocol_slug, vault_address)
Check if a vault is a special vault that may not have deposit/redeem event data.
GRVT and Hyperliquid vaults get data from off-chain APIs
Hardcoded protocol vaults may lack standard ERC-4626 deposit/redeem events
- clean_lifetime_metrics(lifetime_data_df, broken_max_nav_value=99000000000, lifetime_min_nav_threshold=100.0, max_annualised_return=3.0, min_events=25, logger=<built-in function print>)
Filter lifetime metrics by NAV, activity and available annualised returns.
Apply the shared analysis filters to records from
calculate_lifetime_metrics(). Unavailable CAGR is expected for young vaults and does not remove otherwise eligible absolute returns.- Parameters
lifetime_data_df (pandas.DataFrame) – Lifetime records indexed by name or row ID, with numeric or nullable
cagr,peak_navandevent_countplus protocol/address columns.broken_max_nav_value (float) – Maximum accepted lifetime peak assets in denomination units.
lifetime_min_nav_threshold (float) – Minimum lifetime peak assets in denomination units.
max_annualised_return (float) – Exclusive upper bound for available CAGR;
3.0means 300%.min_events (int) – Minimum discovery events, except for supported special vault families.
logger (collections.abc.Callable[[str], None]) – Progress callback.
- Returns
Cleaned lifetime dataframe
- Return type
- combine_return_columns(gross, net, new_line=' ', mode='percent', profit_presentation='split')
Create combined net / (gross) returns column for display.
Display values such as
8.3% (10.5%)while keeping missing values distinct from real zero returns or zero assets. The two input series must share an index; formatting preserves that index.- Parameters
gross (pandas.Series) – Numeric or nullable gross returns, or peak assets in USD mode.
net (pandas.Series) – Numeric or nullable net returns, or current assets in USD mode.
new_line (str) – Separator between the net value and parenthesised gross value.
mode (Literal['percent', 'usd']) – Percentage returns or denomination-unit asset values.
profit_presentation (Literal['split', 'net_only']) – Show both values, or prefer net with gross as the fallback.
- Returns
Combined string series
- Return type
- format_lifetime_table(df, add_index=False, add_address=False, add_share_token=False, drop_blacklisted=True, profit_presentation='split', html_links=False)
Format table for human readable output.
Format the numeric and nullable fields from
calculate_lifetime_metrics()as display text. Missing returns and risk metrics render as---rather than suggesting zero performance.- Parameters
df (pandas.DataFrame) – Lifetime metric records with numeric or nullable returns, risk metrics and vault metadata columns.
add_index (bool) – Add 1, 2, 3… index column
add_address (bool) –
Add address as a separate column.
For vault address list copy-pasted.
add_share_token (bool) – Include the share-token symbol as a separate column.
drop_blacklisted (bool) – Remove vaults we have manually flagged as troublesome.
profit_presentation (Literal['split', 'net_only']) – Show net and gross returns together, or only the net return.
html_links (bool) –
Wrap Name, Chain, and Protocol values in
<a>tags linking to tradingstrategy.ai. Usedisplay_lifetime_table()to render the result with compact styling in a Jupyter notebook.Example:
from eth_defi.research.vault_metrics import ( format_lifetime_table, display_lifetime_table, ) formatted = format_lifetime_table(df, html_links=True) display_lifetime_table(formatted)
- Returns
Human readable data frame
- Return type
- display_lifetime_table(df)
Render a formatted lifetime table as compact HTML in a Jupyter notebook.
Produces an HTML table with minimal cell padding and renders
<a>links created byformat_lifetime_table()withhtml_links=True.Example:
formatted = format_lifetime_table(df, html_links=True) display_lifetime_table(formatted)
- Parameters
df (pandas.DataFrame) – DataFrame returned by
format_lifetime_table().
- class VaultReport
Bases:
objectOne vault data analysed
- rolling_returns_chart: plotly.graph_objs._figure.Figure
Rolling returns chart
- hourly_df: pandas.DataFrame
All hourly columns
- __init__(vault_metadata, rolling_returns_chart, performance_stats, daily_returns, hourly_returns, hourly_df)
- Parameters
vault_metadata (dict) –
rolling_returns_chart (plotly.graph_objs._figure.Figure) –
performance_stats (ffn.core.PerformanceStats) –
daily_returns (pandas.Series) –
hourly_returns (pandas.Series) –
hourly_df (pandas.DataFrame) –
- Return type
None
- analyse_vault(vault_db, prices_df, spec, returns_col='returns_1h', logger=<built-in function print>, chart_frequency='daily')
Create charts and tables to analyse a vault performance.
We plot our annualised 1 month rolling returns on the chart, to see how vaults move in the direction of the markets, or what kind of outliers there are
- Parameters
vault_db (eth_defi.vault.vaultdb.VaultDatabase) – Database of all vault metadata
price_df –
Cleaned price and returns data for all vaults.
Can be be in any time frame.
id – Vault chain + address to analyse, e.g. “1-0x1234567890abcdef1234567890abcdef12345678”
chart_frequency (Literal['hourly', 'daily']) –
Do we plot based on daily or hourly datapoints.
Hourly data has too many points, chocking Plotly.
prices_df (pandas.DataFrame) –
spec (eth_defi.vault.base.VaultSpec) –
returns_col (str) –
- Returns
Analysis report to display.
None if the vault does not have price data.
- Return type
- calculate_performance_metrics_for_all_vaults(vault_db, prices_df, logger=<built-in function print>, lifetime_min_nav_threshold=100.0, broken_max_nav_value=99000000000, cagr_too_high=10000, min_events=25)
Calculate performance metrics for each vault.
Apply NAV, event-count and extreme-CAGR filters to stablecoin vault metrics. Young vaults with valid absolute returns remain eligible while their CAGR is unavailable. This helper expects cleaned price observations; callers requiring daily flow estimates must prepare daily states first.
- Parameters
vault_db (eth_defi.vault.vaultdb.VaultDatabase) – Stablecoin vault metadata keyed by vault identity.
prices_df (pandas.DataFrame) – Timestamp-indexed cleaned observations with vault IDs, prices and assets.
logger (collections.abc.Callable[[str], None]) – Progress callback.
lifetime_min_nav_threshold (float) – Minimum lifetime peak assets in denomination units.
broken_max_nav_value (float) – Maximum accepted lifetime peak assets in denomination units.
cagr_too_high (float) – Exclusive upper bound for available lifetime CAGR.
min_events (int) – Minimum discovery events, except for supported special vault families.
- Returns
DataFrame with lifetime metrics for each vault, indexed by vault name.
- Return type
- format_vault_database(vault_db, index=True)
Format vault database for human readable output.
- Parameters
vault_db (eth_defi.vault.vaultdb.VaultDatabase) – Vault database to format
- Returns
DataFrame with vault metadata, with human readable columns
- Return type
- format_vault_header(vault_row)
Format vault header for human readable output.
- Returns
DataFrame with formatted performance metrics
- Parameters
vault_row (pandas.Series) –
- Return type
- format_ffn_performance_stats(report, prefix_series=None)
Format FFN report for human readable output.
Return a Series with formatted performance metrics
Multiple series can be combined to a comparison table
- Parameters
prefix_data – Extra header data to insert.
report (ffn.core.PerformanceStats) – FFN performance report to format
prefix_series (Optional[pandas.Series]) –
- Returns
DataFrame with formatted performance metrics
- Return type
- FFN_GROUP_HEADINGS = ['Overview', 'Returns', 'Period returns', 'Daily statistics', 'Monthly statistics', 'Yearly statistics', 'Drawdown statistics']
Group headings for FFN performance stats, matching the None separators in
PerformanceStats._stats().
- format_ffn_performance_stats_grouped(report, prefix_series=None)
Format FFN report as logically grouped sections.
Returns a list of
(heading, series)tuples where each tuple represents a group of related metrics. The groups correspond to theNoneseparators in FFN’sPerformanceStats._stats().- Parameters
report (ffn.core.PerformanceStats) – FFN performance report to format.
prefix_series (Optional[pandas.Series]) – Extra header data to prepend to the first group.
- Returns
List of
(heading, series)tuples for each logical group.- Return type
- cross_check_data(vault_db, prices_df, printer=<built-in function print>)
Check that each price identity has a vault metadata entry.
Hourly price data repeats each chain and address many times. Deduplicate these columns before building string keys so the check scales with the number of vaults rather than the number of price rows. The
idcolumn is deliberately not used: the existing check validates chain and address.- Parameters
vault_db (eth_defi.vault.vaultdb.VaultDatabase) – Metadata keyed by chain and address.
prices_df (pandas.DataFrame) – Price rows containing
chainandaddresscolumns.printer (collections.abc.Callable[[str], None]) – Report one message per distinct missing vault identity.
- Returns
Number of distinct missing vault identities; normally zero.
- Return type
- calculate_daily_returns_for_all_vaults(df_work)
Calculate consecutive calendar-day returns for each vault.
Sparse price observations are forward filled independently per vault. Antarctic retains event timestamps and returns between actual observations.
- Parameters
df_work (pandas.DataFrame) – Vault price rows with a
timestampcolumn andchain,addressandshare_pricecolumns.- Returns
Daily vault rows with a
daily_returnspercentage-return column.- Return type
- calculate_hourly_returns_for_all_vaults(df_work)
Calculate consecutive daily returns under a historical API name.
Despite the function and
returns_1hcolumn names, this compatibility helper resamples polled prices to daily frequency. Antarctic retains actual event timestamps and observation-to-observation returns; period analytics regularise its curve separately.- Parameters
df_work (pandas.DataFrame) – Vault price rows indexed by timestamp, with
chain,addressandshare_pricecolumns.- Returns
Daily vault rows with the compatibility column
returns_1h.- Return type
- calculate_sparse_daily_returns_for_all_vaults(df_work)
Regularise daily closing observations for lifetime metric states.
The private crypto price Parquet already contains the final real row for each vault and UTC day, plus an optional first observation before the first day’s close. That initial observation is passed separately to the metrics endpoint calculation. Calendar gaps still need forward-filled prices, while flow columns and observed-state markers must remain sparse.
- Parameters
df_work (pandas.DataFrame) – Sparse daily vault prices with a timestamp index and at most one row per
chain,addressand UTC day, except two distinct real observations on the first day.- Returns
Consecutive daily rows with the compatibility
returns_1hcolumn.- Return type
- display_vault_chart_and_tearsheet(vault_spec, vault_db, prices_df, render=True)
Render a chart and tearsheet for a single vault.
Use in notebooks
- :param render;
Disable rendering in tests
- Parameters
vault_spec (eth_defi.vault.base.VaultSpec) –
vault_db (eth_defi.vault.vaultdb.VaultDatabase) –
prices_df (pandas.DataFrame) –
- export_lifetime_row(row)
Export lifetime metrics row to a fully JSON-serialisable dict.
Recursively handles nested dicts, lists, tuples, sets, and dataclasses.
Normalises pandas, numpy, datetime, and custom types.
Converts finite
Decimalvalues to JSON number floats.Preserves legacy fee field names.
The
share_price_sourcecolumn is retained as a stableeth_defi.vault.price_source.PriceSourcestring value.The
denomination_token_ratedataclass frometh_defi.feed.stablecoin_rate.DenominationTokenRateis converted to JSON fields here. This includesusd_rate/usd_rate_fetched_atfor all stablecoins andnative_rate/native_rate_fetched_atonly when the native source currency is not USD.- Parameters
row (pandas.Series) –
- Return type