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_coingecko_mapping_file(data_dir, ...)

Apply explicit CoinGecko id mappings to stablecoin YAML files.

build_depegged_stablecoin_lookups([data_dir])

Build contract and unambiguous symbol lookups for depegged stablecoins.

build_stablecoin_rate_lookups([data_dir])

Build contract and unambiguous symbol lookups for all known rate data.

extract_coingecko_id(url)

Extract a CoinGecko coin id from a human-readable CoinGecko URL.

fetch_stablecoin_rates(targets[, timeout, ...])

Fetch CoinGecko prices for due stablecoin targets.

fetch_valid_coingecko_ids(coin_ids[, ...])

Validate CoinGecko coin ids against the canonical coins list endpoint.

iter_stablecoin_rate_targets([data_dir])

Iterate stablecoin YAML entries that can participate in rate refreshes.

read_latest_usd_per_source_currency(...[, ...])

Read the latest USD/source-currency FX rate from local DuckDB.

refresh_stablecoin_rates([data_dir, now_, ...])

Refresh stablecoin rates and persist YAML metadata updates.

resolve_coingecko_metadata(entry)

Resolve the CoinGecko id, page link, and id source for one YAML entry.

Classes

DenominationTokenRate

Rate data section exported for a vault denomination token.

SourceCurrencyRate

USD/source-currency rate read from the local currency DuckDB.

StablecoinRateFeeder

Cached stablecoin rate/depeg lookup helper for vault metrics.

StablecoinRateRefreshSummary

Counters for one stablecoin rate refresh run.

StablecoinRateTarget

One stablecoin YAML entry that may be refreshed from CoinGecko.

class StablecoinRateTarget

Bases: object

One 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. Only manual values drive depeg checks.

source_currency_usd_rate: Optional[float]

USD per one source_currency unit 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_rate was 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: true in the YAML for tickers such as sUSD or USDR that 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: true in 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 no contract_addresses entry 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
Return type

None

class StablecoinRateRefreshSummary

Bases: object

Counters for one stablecoin rate refresh run.

skipped_missing_source_currency: int

Entries skipped because no source currency is known.

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_currency was 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: object

USD/source-currency rate read from the local currency DuckDB.

source_currency: str

Lower-case source currency ticker, e.g. eur or jpy.

usd_per_source_currency: float

USD per one source_currency unit.

date: datetime.date

Currency API calendar date for usd_per_source_currency.

source: str

Currency API provider/source column.

is_stale: bool

True when the FX row is older than the accepted refresh delay.

__init__(source_currency, usd_per_source_currency, date, source, is_stale)
Parameters
Return type

None

class DenominationTokenRate

Bases: object

Rate data section exported for a vault denomination token.

This dataclass is returned by StablecoinRateFeeder.get_denomination_token_rate_section() and is serialised by eth_defi.research.vault_metrics.export_lifetime_row() for the denomination_token_rate field in lifetime metrics JSON output. Source-currency values originate from eth_defi.stablecoin_metadata.StablecoinMetadata and are updated by refresh_stablecoin_rates().

coingecko_id: Optional[str]

CoinGecko coin id used to fetch usd_rate.

source_currency: Optional[str]

Stablecoin source currency ticker, e.g. usd, eur or jpy.

usd_rate: Optional[float]

Latest token price in USD from CoinGecko.

usd_rate_fetched_at: Optional[datetime.datetime]

Naive UTC timestamp when usd_rate was fetched.

usd_rate_source: Optional[str]

Provider/source for usd_rate. Currently coingecko when present.

native_rate: Optional[float]

Latest token price in source_currency for non-USD stablecoins.

This is omitted for source_currency == "usd" because usd_rate already 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. Matches usd_rate_fetched_at when populated.

native_rate_source: Optional[str]

Provider chain for native_rate, e.g. coingecko+fawazahmed0.

source_currency_usd_rate: Optional[float]

USD per one source_currency unit used to derive native_rate.

source_currency_usd_rate_fetched_at: Optional[datetime.datetime]

Naive UTC timestamp when source_currency_usd_rate was 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
Return type

None

class StablecoinRateFeeder

Bases: object

Cached 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

eth_defi.feed.stablecoin_rate.DenominationTokenRate

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 True when a denomination token is marked depegged.

Parameters
Return type

bool

__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.

Parameters

url (Optional[str]) –

Return type

Optional[str]

resolve_coingecko_metadata(entry)

Resolve the CoinGecko id, page link, and id source for one YAML entry.

Parameters

entry (dict[str, Any]) –

Return type

tuple[str | None, str | None, str | None]

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
Returns

CoinGecko response keyed by coin id.

Return type

dict[str, dict[str, Any]]

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_id or deriving a human-readable coingecko_link.

Parameters
  • coin_ids (Sequence[str]) – CoinGecko ids to validate.

  • timeout (float) – HTTP request timeout in seconds.

  • progress_bar (bool) – Show a tqdm progress bar for validation requests.

Returns

Set of ids that resolved to real CoinGecko coins.

Return type

set[str]

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 quote units per one base unit. With the production base usd this means, for example, EUR rows are EUR 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. eur or jpy.

  • 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 None when no local row exists.

Return type

Optional[eth_defi.feed.stablecoin_rate.SourceCurrencyRate]

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
Return type

eth_defi.feed.stablecoin_rate.StablecoinRateRefreshSummary

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 a depegged_at marker, 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 USDX are 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 by contract_addresses in 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).

Parameters

data_dir (pathlib.Path) – Directory of stablecoin metadata YAML files.

Returns

Tuple of (depegged_contract_keys, depegged_symbols).

Return type

tuple[set[tuple[int, str]], set[str]]

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
Return type

int