feed.stablecoin_rate
Documentation for eth_defi.feed.stablecoin_rate Python module.
Stablecoin rate refresh and depeg lookups.
This module maintains mutable rate metadata in
eth_defi/data/stablecoins/*.yaml. It fetches stablecoin prices from the
CoinGecko simple price API, stores the latest USD rate and fetch timestamp, and
marks a sticky depegged_at timestamp when a token trades below the
configured threshold in its manually curated source currency. Non-USD source
currencies are converted through the local
CurrencyRateDatabase before depeg
checks are made.
Vault metric calculation should use StablecoinRateFeeder instead of
reading YAML files directly. The feeder owns the in-process lookup caches used
to resolve a vault denomination token to stablecoin rate metadata. The returned
DenominationTokenRate is exported by
eth_defi.research.vault_metrics.calculate_lifetime_metrics() under the
denomination_token_rate JSON field.
See CoinGecko simple price documentation and CoinGecko coins list documentation.
Functions
|
Apply explicit CoinGecko id mappings to stablecoin YAML files. |
|
Build contract and unambiguous symbol lookups for depegged stablecoins. |
|
Build contract and unambiguous symbol lookups for all known rate data. |
|
Extract a CoinGecko coin id from a human-readable CoinGecko URL. |
|
Fetch CoinGecko prices for due stablecoin targets. |
|
Validate CoinGecko coin ids against the canonical coins list endpoint. |
|
Iterate stablecoin YAML entries that can participate in rate refreshes. |
|
Read the latest USD/source-currency FX rate from local DuckDB. |
|
Refresh stablecoin rates and persist YAML metadata updates. |
|
Resolve the CoinGecko id, page link, and id source for one YAML entry. |
Classes
Rate data section exported for a vault denomination token. |
|
USD/source-currency rate read from the local currency DuckDB. |
|
Cached stablecoin rate/depeg lookup helper for vault metrics. |
|
Counters for one stablecoin rate refresh run. |
|
One stablecoin YAML entry that may be refreshed from CoinGecko. |
- class StablecoinRateTarget
Bases:
objectOne stablecoin YAML entry that may be refreshed from CoinGecko.
- source_currency: Optional[str]
Curated source currency ticker read from
eth_defi.stablecoin_metadata.StablecoinMetadata.
- source_currency_source: Optional[str]
Source of
source_currency. Onlymanualvalues drive depeg checks.
- source_currency_usd_rate: Optional[float]
USD per one
source_currencyunit from the local currency database.
- source_currency_usd_rate_date: Optional[datetime.date]
Calendar date of
source_currency_usd_rate.
- source_currency_usd_rate_fetched_at: Optional[datetime.datetime]
Naive UTC timestamp when
source_currency_usd_ratewas read.
- source_currency_usd_rate_source: Optional[str]
Currency API source column used for
source_currency_usd_rate.
- ambiguous_symbol: bool
The ticker is reused by unrelated tokens, so never match this entry by symbol — only by contract address. Set
ambiguous_symbol: truein the YAML for tickers such assUSDorUSDRthat several distinct tokens share, otherwise marking one depegged would blacklist the healthy ones.
- non_evm: bool
The token has no ERC-20 deployment on any chain we index, so it can never denominate an EVM vault and there is nothing to blacklist. Set
non_evm: truein the YAML for natively non-EVM tokens (e.g. Acala aUSD on Polkadot, Kava USDX on Cosmos) to silence the otherwise-unactionable depeg warning, which nocontract_addressesentry could ever resolve.
- __init__(yaml_path, entry_index, slug, symbol, category, name, coingecko_id, coingecko_link, coingecko_id_source, coingecko_id_verified_at, coingecko_id_verification_failed_at, coingecko_id_verification_failed_reason, source_currency, source_currency_source, source_currency_usd_rate, source_currency_usd_rate_date, source_currency_usd_rate_fetched_at, source_currency_usd_rate_source, peg_currency, usd_rate, usd_rate_fetched_at, usd_rate_updated_at, peg_rate, peg_rate_currency, rate_fetch_failed_at, rate_fetch_failed_reason, depegged_at, contract_addresses, ambiguous_symbol=False, non_evm=False)
- Parameters
yaml_path (pathlib.Path) –
slug (str) –
symbol (str) –
category (str) –
name (str) –
coingecko_id_verified_at (Optional[datetime.datetime]) –
coingecko_id_verification_failed_at (Optional[datetime.datetime]) –
source_currency_usd_rate_date (Optional[datetime.date]) –
source_currency_usd_rate_fetched_at (Optional[datetime.datetime]) –
usd_rate_fetched_at (Optional[datetime.datetime]) –
usd_rate_updated_at (Optional[datetime.datetime]) –
rate_fetch_failed_at (Optional[datetime.datetime]) –
depegged_at (Optional[datetime.datetime]) –
ambiguous_symbol (bool) –
non_evm (bool) –
- Return type
None
- class StablecoinRateRefreshSummary
Bases:
objectCounters for one stablecoin rate refresh run.
- skipped_missing_source_currency_rate: int
Non-USD entries skipped because no usable currency database row existed.
- skipped_inferred_source_currency: int
Entries skipped because
source_currencywas not manually curated.
- source_currency_rates_fetched: int
Source-currency FX rows accepted from the local currency database.
- source_currency_rates_stale: int
Source-currency FX rows rejected because they were older than the allowed delay.
- __init__(files_scanned=0, entries_seen=0, due_count=0, skipped_attempted_today_count=0, skipped_failed_today_count=0, skipped_succeeded_today_count=0, rates_fetched=0, files_updated=0, depegged_count=0, unactionable_depegged_count=0, skipped_missing_coingecko=0, skipped_unknown_peg=0, skipped_missing_source_currency=0, skipped_missing_source_currency_rate=0, skipped_inferred_source_currency=0, source_currency_rates_fetched=0, source_currency_rates_stale=0, failed_count=0, coingecko_ids_checked=0, coingecko_ids_valid=0, coingecko_id_validation_failed_count=0)
- Parameters
files_scanned (int) –
entries_seen (int) –
due_count (int) –
skipped_attempted_today_count (int) –
skipped_failed_today_count (int) –
skipped_succeeded_today_count (int) –
rates_fetched (int) –
files_updated (int) –
depegged_count (int) –
unactionable_depegged_count (int) –
skipped_missing_coingecko (int) –
skipped_unknown_peg (int) –
skipped_missing_source_currency (int) –
skipped_missing_source_currency_rate (int) –
skipped_inferred_source_currency (int) –
source_currency_rates_fetched (int) –
source_currency_rates_stale (int) –
failed_count (int) –
coingecko_ids_checked (int) –
coingecko_ids_valid (int) –
coingecko_id_validation_failed_count (int) –
- Return type
None
- class SourceCurrencyRate
Bases:
objectUSD/source-currency rate read from the local currency DuckDB.
- date: datetime.date
Currency API calendar date for
usd_per_source_currency.
- class DenominationTokenRate
Bases:
objectRate data section exported for a vault denomination token.
This dataclass is returned by
StablecoinRateFeeder.get_denomination_token_rate_section()and is serialised byeth_defi.research.vault_metrics.export_lifetime_row()for thedenomination_token_ratefield in lifetime metrics JSON output. Source-currency values originate frometh_defi.stablecoin_metadata.StablecoinMetadataand are updated byrefresh_stablecoin_rates().- usd_rate_fetched_at: Optional[datetime.datetime]
Naive UTC timestamp when
usd_ratewas fetched.
- native_rate: Optional[float]
Latest token price in
source_currencyfor non-USD stablecoins.This is omitted for
source_currency == "usd"becauseusd_ratealready carries the native value.
- native_rate_currency: Optional[str]
Currency ticker for
native_rate. Populated only for non-USD source currencies.
- native_rate_fetched_at: Optional[datetime.datetime]
Naive UTC timestamp for
native_rate. Matchesusd_rate_fetched_atwhen populated.
- source_currency_usd_rate: Optional[float]
USD per one
source_currencyunit used to derivenative_rate.
- source_currency_usd_rate_fetched_at: Optional[datetime.datetime]
Naive UTC timestamp when
source_currency_usd_ratewas read from the currency database.
- source_currency_usd_rate_source: Optional[str]
Currency database provider/source for
source_currency_usd_rate.
- __init__(coingecko_id, source_currency, usd_rate, usd_rate_fetched_at, usd_rate_source, native_rate, native_rate_currency, native_rate_fetched_at, native_rate_source, source_currency_usd_rate, source_currency_usd_rate_fetched_at, source_currency_usd_rate_source)
- Parameters
usd_rate_fetched_at (Optional[datetime.datetime]) –
native_rate_fetched_at (Optional[datetime.datetime]) –
source_currency_usd_rate_fetched_at (Optional[datetime.datetime]) –
- Return type
None
- class StablecoinRateFeeder
Bases:
objectCached stablecoin rate/depeg lookup helper for vault metrics.
- get_denomination_token_rate_section(chain_id, address, symbol)
Resolve a vault denomination token to exported rate metadata.
- Parameters
- Return type
- property depegged_contracts: set[tuple[int, str]]
Set of
(chain_id, lowercased_address)keys for depegged tokens (built lazily, cached).
- property depegged_symbols: set[str]
Set of unambiguously depegged normalised symbols (built lazily, cached).
- is_depegged_stablecoin_token(chain_id, address, symbol)
Return
Truewhen a denomination token is marked depegged.
- __init__(data_dir=PosixPath('/home/runner/work/web3-ethereum-defi/web3-ethereum-defi/eth_defi/data/stablecoins'))
- Parameters
data_dir (pathlib.Path) –
- Return type
None
- extract_coingecko_id(url)
Extract a CoinGecko coin id from a human-readable CoinGecko URL.
- resolve_coingecko_metadata(entry)
Resolve the CoinGecko id, page link, and id source for one YAML entry.
- iter_stablecoin_rate_targets(data_dir=PosixPath('/home/runner/work/web3-ethereum-defi/web3-ethereum-defi/eth_defi/data/stablecoins'))
Iterate stablecoin YAML entries that can participate in rate refreshes.
- Parameters
data_dir (pathlib.Path) –
- Return type
Iterator[eth_defi.feed.stablecoin_rate.StablecoinRateTarget]
- fetch_stablecoin_rates(targets, timeout=20.0, progress_bar=False)
Fetch CoinGecko prices for due stablecoin targets.
- Parameters
targets (Sequence[eth_defi.feed.stablecoin_rate.StablecoinRateTarget]) – Due targets with resolved CoinGecko ids.
timeout (float) – HTTP request timeout in seconds.
progress_bar (bool) – Show a tqdm progress bar for CoinGecko request batches.
- Returns
CoinGecko response keyed by coin id.
- Return type
- fetch_valid_coingecko_ids(coin_ids, timeout=20.0, progress_bar=False)
Validate CoinGecko coin ids against the canonical coins list endpoint.
CoinGecko web pages can redirect or fall back to search pages for stale slugs. The collector therefore validates ids with the API before exporting
coingecko_idor deriving a human-readablecoingecko_link.
- read_latest_usd_per_source_currency(currency_db_path, source_currency, coingecko_fetch_date, source='fawazahmed0', max_age_days=7)
Read the latest USD/source-currency FX rate from local DuckDB.
The currency API database stores raw rows as
quoteunits per onebaseunit. With the production baseusdthis means, for example, EUR rows areEUR per 1 USD. Stablecoin depeg checks need USD per one source-currency unit, so this helper inverts the stored raw rate.- Parameters
currency_db_path (pathlib.Path) – DuckDB path populated by
eth_defi.currency_api.source_currency (str) – Lower-case source currency ticker, e.g.
eurorjpy.coingecko_fetch_date (datetime.date) – Calendar date of the CoinGecko token price fetch.
source (str) – Currency API source column to read.
max_age_days (int) – Maximum allowed age between the token price date and FX row date.
- Returns
USD per one source-currency unit, or
Nonewhen no local row exists.- Return type
- refresh_stablecoin_rates(data_dir=PosixPath('/home/runner/work/web3-ethereum-defi/web3-ethereum-defi/eth_defi/data/stablecoins'), now_=None, force=False, timeout=20.0, progress_bar=False, currency_db_path=None, currency_source='fawazahmed0')
Refresh stablecoin rates and persist YAML metadata updates.
This function is intentionally entry tolerant: missing CoinGecko ids and missing prices are written to per-entry failure fields instead of aborting the whole run. HTTP-level failures are recorded for all due targets in the batch, then returned in the summary. Depeg decisions are made only when the token’s peg currency can be inferred and CoinGecko returns that currency.
- Parameters
data_dir (pathlib.Path) –
now_ (Optional[datetime.datetime]) –
force (bool) –
timeout (float) –
progress_bar (bool) –
currency_db_path (Optional[pathlib.Path]) –
currency_source (str) –
- Return type
- build_depegged_stablecoin_lookups(data_dir=PosixPath('/home/runner/work/web3-ethereum-defi/web3-ethereum-defi/eth_defi/data/stablecoins'))
Build contract and unambiguous symbol lookups for depegged stablecoins.
Determine which denomination tokens should be treated as depegged for vault blacklisting. Two independent lookups are returned:
A set of
(chain_id, lowercased_address)contract keys for every entry that carries adepegged_atmarker, regardless of whether the entry lives in a single- or multi-entry YAML file. This is the precise path: it pins the dead token by address and never blacklists an unrelated token that merely reuses the same ticker.A set of normalised symbols that are unambiguously depegged. A symbol is only eligible here when a single flat (single-entry) YAML file owns it and that file is marked
depegged_at.
Symbol matching is deliberately not used for multi-entry tokens. Tickers such as
USDXare reused by several unrelated tokens in the wild — e.g. the dead Stables Labs USDX (0xf3527ef8…) versus the live Axis USD (USDx) on Plasma — so matching by ticker would blacklist healthy vaults. Multi-entry depegged tokens must therefore be pinned bycontract_addressesin their YAML entry. A warning is logged for any depegged entry that has no contract address and is not covered by an unambiguous symbol, because such a depeg silently fails to blacklist anything (this is the gap that previously let USDX-denominated vaults stay listed).
- build_stablecoin_rate_lookups(data_dir=PosixPath('/home/runner/work/web3-ethereum-defi/web3-ethereum-defi/eth_defi/data/stablecoins'))
Build contract and unambiguous symbol lookups for all known rate data.
- Parameters
data_dir (pathlib.Path) –
- Return type
tuple[dict[tuple[int, str], eth_defi.feed.stablecoin_rate.DenominationTokenRate], dict[str, eth_defi.feed.stablecoin_rate.DenominationTokenRate]]
- apply_coingecko_mapping_file(data_dir, mapping_path, progress_bar=False)
Apply explicit CoinGecko id mappings to stablecoin YAML files.
The mapping JSON shape is intentionally simple:
{ "usdx": { "Kava USDX": { "coingecko_id": "usdx", "coingecko_link": "https://www.coingecko.com/en/coins/usdx" } } }
Top-level keys are stablecoin slugs. For multi-entry files, the nested key can be the entry name or a numeric entry index encoded as a string. Standard files may use
"default".- Parameters
data_dir (pathlib.Path) –
mapping_path (pathlib.Path) –
progress_bar (bool) –
- Return type