eth_portfolio.typing package
Module contents
This module defines a set of classes to represent and manipulate various levels of balance structures within an Ethereum portfolio. The focus of these classes is on reading, aggregating, and summarizing balances, including the value in both tokens and their equivalent in USD.
The main classes and their purposes are as follows:
Balance
: Represents the balance of a single token, including its token amount and equivalent USD value.TokenBalances
: Manages a collection ofBalance
objects for multiple tokens, providing operations such as summing balances across tokens.RemoteTokenBalances
: ExtendsTokenBalances
to manage balances across different protocols, enabling aggregation and analysis of balances by protocol.WalletBalances
: Organizes token balances into categories such as assets, debts, and external balances for a single wallet. It combinesTokenBalances
andRemoteTokenBalances
to provide a complete view of a wallet’s balances.PortfolioBalances
: AggregatesWalletBalances
for multiple wallets, providing operations to sum balances across an entire portfolio.WalletBalancesRaw
: Similar toWalletBalances
, but with a key structure optimized for accessing balances directly by wallet and token.PortfolioBalancesByCategory
: Provides an inverted view ofPortfolioBalances
, allowing access by category first, then by wallet and token.
These classes are designed for efficient parsing, manipulation, and summarization of portfolio data, without managing or altering any underlying assets.
- final class eth_portfolio.typing.PortfolioBalances[source]
Bases:
DefaultChecksumDict
[WalletBalances
],_SummableNonNumericMixin
Aggregates
WalletBalances
for multiple wallets, providing operations to sum balances across an entire portfolio.The class uses wallet addresses as keys and
WalletBalances
objects as values.- Parameters:
seed – An initial seed of portfolio balances, either as a dictionary or an iterable of tuples.
Example
>>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})})}) >>> portfolio_balances['0x123']['assets']['0x456'].balance Decimal('100')
- __getitem__(key, /)
Return self[key].
- __init__(seed=None, *, block=None)[source]
- Parameters:
seed (Dict[str | HexBytes | AnyAddress | Address | EthAddress, WalletBalances] | Iterable[Tuple[str | HexBytes | AnyAddress | Address | EthAddress, WalletBalances]] | None)
block (BlockNumber | None)
- Return type:
None
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- sum_usd()[source]
Sums the USD values of all wallet balances in the portfolio.
- Returns:
The total USD value of all wallet balances in the portfolio.
- Return type:
Decimal
Example
>>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})}) >>> total_usd = portfolio_balances.sum_usd() >>> total_usd Decimal('2000')
- values() an object providing a view on D's values
- property dataframe: DataFrame
Converts the portfolio balances into a pandas DataFrame.
- Returns:
A DataFrame representation of the portfolio balances.
- property inverted: PortfolioBalancesByCategory
Returns an inverted view of the portfolio balances, grouped by category first.
- Returns:
The inverted portfolio balances, grouped by category.
- Return type:
Example
>>> portfolio_balances = PortfolioBalances({'0x123': WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})}) >>> inverted_pb = portfolio_balances.inverted >>> inverted_pb['assets']['0x123'].balance Decimal('100')
- final class eth_portfolio.typing.PortfolioBalancesByCategory[source]
Bases:
DefaultDict
[Literal
[‘assets’, ‘debt’, ‘external’],WalletBalancesRaw
],_SummableNonNumericMixin
Provides an inverted view of
PortfolioBalances
, allowing access by category first, then by wallet and token.The class uses category labels as keys (assets, debt, external) and
WalletBalancesRaw
objects as values.- Parameters:
seed – An initial seed of portfolio balances by category, either as a dictionary or an iterable of tuples.
Example
>>> pb_by_category = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})})}) >>> pb_by_category['assets']['0x123']['0x456'].balance Decimal('100')
- __getitem__()
x.__getitem__(y) <==> x[y]
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- invert()[source]
Inverts the portfolio balances by category to group by wallet first.
- Returns:
The inverted portfolio balances, grouped by wallet first.
- Return type:
Example
>>> pb_by_category = PortfolioBalancesByCategory({'assets': WalletBalancesRaw({'0x123': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})})}) >>> inverted_pb = pb_by_category.invert() >>> inverted_pb['0x123']['assets']['0x123'].balance Decimal('100')
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- values() an object providing a view on D's values
- property assets: WalletBalancesRaw
Returns the asset balances across all wallets.
- Returns:
The
WalletBalancesRaw
object representing the asset balances.- Return type:
- property debt: WalletBalancesRaw
Returns the debt balances across all wallets.
- Returns:
The
WalletBalancesRaw
object representing the debt balances.- Return type:
- final class eth_portfolio.typing.RemoteTokenBalances[source]
Bases:
DefaultDict
[str
,TokenBalances
],_SummableNonNumericMixin
Manages token balances across different protocols, extending the
TokenBalances
functionality to multiple protocols.The class uses protocol labels as keys and
TokenBalances
objects as values.- Parameters:
seed – An initial seed of remote token balances, either as a dictionary or an iterable of tuples.
Example
>>> remote_balances = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})}) >>> remote_balances['protocol1']['0x123'].balance Decimal('100')
- __getitem__()
x.__getitem__(y) <==> x[y]
- __init__(seed=None, *, block=None)[source]
- Parameters:
seed (Dict[str, TokenBalances] | None)
block (BlockNumber | None)
- Return type:
None
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- sum_usd()[source]
Sums the USD values of all token balances across all protocols.
- Returns:
The total USD value of all remote token balances.
- Return type:
Decimal
Example
>>> remote_balances = RemoteTokenBalances({'protocol1': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})}) >>> total_usd = remote_balances.sum_usd() >>> total_usd Decimal('2000')
- values() an object providing a view on D's values
- final class eth_portfolio.typing.TokenBalances[source]
Bases:
DefaultChecksumDict
[Balance
],_SummableNonNumericMixin
A specialized defaultdict subclass made for holding a mapping of
token -> balance
.Manages a collection of
Balance
objects for multiple tokens, allowing for operations such as summing balances across tokens.The class uses token addresses as keys and
Balance
objects as values. It supports arithmetic operations like addition and subtraction of token balances.Token addresses are checksummed automatically when adding items to the dict, and the default value for a token not present is an empty
Balance
object.- Parameters:
seed – An initial seed of token balances, either as a dictionary or an iterable of tuples.
Example
>>> token_balances = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))}) >>> token_balances['0x123'].balance Decimal('100')
- __init__(seed=None, *, block=None)[source]
- Parameters:
seed (Dict[str | HexBytes | AnyAddress | Address | EthAddress, Balance] | Iterable[Tuple[str | HexBytes | AnyAddress | Address | EthAddress, Balance]] | None)
block (BlockNumber | None)
- Return type:
None
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- sum_usd()[source]
Sums the USD values of all token balances.
- Returns:
The total USD value of all token balances.
- Return type:
Decimal
Example
>>> token_balances = TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))}) >>> total_usd = token_balances.sum_usd() >>> total_usd Decimal('2000')
- values() an object providing a view on D's values
- final class eth_portfolio.typing.WalletBalances[source]
Bases:
Dict
[Literal
[‘assets’, ‘debt’, ‘external’],TokenBalances
|RemoteTokenBalances
],_SummableNonNumericMixin
Organizes token balances into categories such as assets, debts, and external balances for a single wallet.
The class uses categories as keys (assets, debt, external) and
TokenBalances
orRemoteTokenBalances
objects as values.- Parameters:
seed – An initial seed of wallet balances, either as a dictionary or an iterable of tuples.
Example
>>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})}) >>> wallet_balances['assets']['0x123'].balance Decimal('100')
- __getitem__(key)[source]
Retrieves the balance associated with the given category key.
- Parameters:
key (Literal['assets', 'debt', 'external']) – The category label (assets, debt, or external).
- Returns:
The balances associated with the category.
- Raises:
KeyError – If the key is not a valid category.
- Return type:
Example
>>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})}) >>> assets_balances = wallet_balances['assets'] >>> assets_balances['0x123'].balance Decimal('100')
- __init__(seed=None, *, block=None)[source]
- Parameters:
seed (WalletBalances | _WalletBalancesTD | Iterable[Tuple[Literal['assets', 'debt', 'external'], ~eth_portfolio.typing.TokenBalances]] | None)
block (BlockNumber | None)
- Return type:
None
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- sum_usd()[source]
Sums the USD values of the wallet’s assets, debts, and external balances.
- Returns:
The total USD value of the wallet’s net assets (assets - debt + external).
- Return type:
Decimal
Example
>>> wallet_balances = WalletBalances({'assets': TokenBalances({'0x123': Balance(Decimal('100'), Decimal('2000'))})}) >>> total_usd = wallet_balances.sum_usd() >>> total_usd Decimal('2000')
- values() an object providing a view on D's values
- property assets: TokenBalances
Returns the assets held by the wallet.
- Returns:
The
TokenBalances
object representing the wallet’s assets.- Return type:
- property dataframe: DataFrame
Converts the wallet balances into a pandas DataFrame.
- Returns:
A DataFrame representation of the wallet balances.
- property debt: RemoteTokenBalances
Returns the debts associated with the wallet.
- Returns:
The
RemoteTokenBalances
object representing the wallet’s debts.- Return type:
- property external: RemoteTokenBalances
Returns the external balances associated with the wallet.
- Returns:
The
RemoteTokenBalances
object representing the wallet’s external balances.- Return type:
- final class eth_portfolio.typing.WalletBalancesRaw[source]
Bases:
DefaultChecksumDict
[TokenBalances
],_SummableNonNumericMixin
A structure for key pattern wallet -> token -> balance.
This class is similar to
WalletBalances
but optimized for key lookups by wallet and token directly. It managesTokenBalances
objects for multiple wallets.- Parameters:
seed – An initial seed of wallet balances, either as a dictionary or an iterable of tuples.
Example
>>> raw_balances = WalletBalancesRaw({'0x123': TokenBalances({'0x456': Balance(Decimal('100'), Decimal('2000'))})}) >>> raw_balances['0x123']['0x456'].balance Decimal('100')
- __getitem__(key, /)
Return self[key].
- __init__(seed=None, *, block=None)[source]
- Parameters:
seed (Dict[str | HexBytes | AnyAddress | Address | EthAddress, TokenBalances] | Iterable[Tuple[str | HexBytes | AnyAddress | Address | EthAddress, TokenBalances]] | None)
block (BlockNumber | None)
- Return type:
None
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- values() an object providing a view on D's values
- class eth_portfolio.typing._SummableNonNumericMixin[source]
Bases:
object
Mixin class for non-numeric summable objects.
This class provides an interface for objects that can be used with sum but are not necessarily numeric.
- class eth_portfolio.typing._WalletBalancesTD
Bases:
dict
- __getitem__()
x.__getitem__(y) <==> x[y]
- __init__(*args, **kwargs)
- __iter__()
Implement iter(self).
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D'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.
- values() an object providing a view on D's values
- assets: TokenBalances
- debt: TokenBalances
- external: RemoteTokenBalances