Skip to content

Commit

Permalink
Merge pull request #170 from curveresearch/pylint
Browse files Browse the repository at this point in the history
Pylint
  • Loading branch information
chanhosuh authored Jul 24, 2023
2 parents 512079e + 8fc9073 commit 2a6759d
Show file tree
Hide file tree
Showing 32 changed files with 358 additions and 276 deletions.
9 changes: 4 additions & 5 deletions curvesim/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ def _python_info():
str:
Implementation name, version, and platform
"""
return "{} {} on {}".format(
platform.python_implementation(),
platform.python_version(),
platform.system(),
)
impl = platform.python_implementation()
version = platform.python_version()
system = platform.system()
return f"{impl} {version} on {system}"


if __name__ == "__main__":
Expand Down
11 changes: 8 additions & 3 deletions curvesim/iterators/param_samplers/parameterized_pool_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class ParameterizedPoolIterator(ParameterSampler):
Iterates over pools with all possible combinations of the input parameters.
"""

# pylint: disable-next=unused-argument
def __new__(cls, pool, variable_params, fixed_params=None, pool_map=None):
"""
Returns a pool-specific ParameterizedPoolIterator subclass.
Expand Down Expand Up @@ -46,6 +47,7 @@ def __new__(cls, pool, variable_params, fixed_params=None, pool_map=None):

return super().__new__(subclass)

# pylint: disable-next=unused-argument
def __init__(self, pool, variable_params, fixed_params=None, pool_map=None):
"""
Parameters
Expand Down Expand Up @@ -144,21 +146,24 @@ def _pool_type(self):

class ParameterizedCurvePoolIterator(CurvePoolMixin, ParameterizedPoolIterator):
"""
:class:`ParameterizedPoolIterator` parameter sampler specialized for Curve pools.
:class:`ParameterizedPoolIterator` parameter sampler specialized
for Curve pools.
"""


class ParameterizedCurveMetaPoolIterator(CurveMetaPoolMixin, ParameterizedPoolIterator):
"""
:class:`ParameterizedPoolIterator` parameter sampler specialized for Curve meta-pools.
:class:`ParameterizedPoolIterator` parameter sampler specialized
for Curve meta-pools.
"""


class ParameterizedCurveCryptoPoolIterator(
CurveCryptoPoolMixin, ParameterizedPoolIterator
):
"""
:class:`ParameterizedPoolIterator` parameter sampler specialized for Curve crypto pools.
:class:`ParameterizedPoolIterator` parameter sampler specialized
for Curve crypto pools.
"""


Expand Down
57 changes: 56 additions & 1 deletion curvesim/iterators/param_samplers/pool_mixins.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from curvesim.pool.sim_interface import SimCurvePool, SimCurveMetaPool
"""
These mixins extend Curve pool classes for the purpose of generating iterables
of pool instances configured by different simulation parameters.
Each mixin defines a different pool type and a set of special attribute setters.
"""

from curvesim.pool.sim_interface import SimCurveMetaPool, SimCurvePool


class CurvePoolMixin:
Expand All @@ -13,6 +20,12 @@ def _pool_type(self):

@property
def setters(self):
"""
Returns
-------
dict
A dictionary containing the special setters for the pool parameters.
"""
return {"D": stableswap_D_to_balances}


Expand All @@ -28,6 +41,12 @@ def _pool_type(self):

@property
def setters(self):
"""
Returns
-------
dict
A dictionary containing the special setters for the pool parameters.
"""
return {"D": stableswap_D_to_balances, "D_base": stableswap_D_base_to_balances}


Expand All @@ -43,23 +62,59 @@ def _pool_type(self):

@property
def setters(self):
"""
Returns
-------
dict
A dictionary containing the special setters for the pool parameters.
"""
return {"D": cryptoswap_D_to_balances}


def stableswap_D_to_balances(pool, D):
"""
Sets the balance for each token in the pool based on the provided
invariant value.
Parameters
----------
pool : instance of _pool_type
D : int
The invariant value.
"""
rates = pool.rates
n = pool.n
pool.balances = [D // n * 10**18 // r for r in rates]


def stableswap_D_base_to_balances(pool, D_base):
"""
Sets the balance for each token in the basepool based on the provided
invariant value.
Parameters
----------
pool : instance of _pool_type
D_base : int
The invariant value for the basepool.
"""
basepool = pool.basepool
rates = basepool.rates
n = basepool.n
basepool.balances = [D_base // n * 10**18 // r for r in rates]


def cryptoswap_D_to_balances(pool, D):
"""
Sets the balance for each token in the pool based on the provided
invariant value.
Parameters
----------
pool : instance of _pool_type
D : int
The invariant value.
"""
n = pool.n
price_scale = pool.price_scale
precisions = pool.precisions
Expand Down
10 changes: 9 additions & 1 deletion curvesim/iterators/price_samplers/price_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,15 @@ class PriceVolume(PriceSampler):
An iterator that retrieves price/volume and iterates over timepoints in the data.
"""

def __init__(self, assets, days=60, data_dir="data", src="coingecko", end=None):
def __init__(
self,
assets,
*,
days=60,
data_dir="data",
src="coingecko",
end=None,
):
"""
Retrieves price/volume data and prepares it for iteration.
Expand Down
47 changes: 31 additions & 16 deletions curvesim/metrics/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ def config(self):
def __init__(self, pool, **kwargs):
super().__init__(pool.assets.symbols)

def compute_arb_metrics(self, price_sample, trade_data, **kwargs):
def compute_arb_metrics(self, **kwargs):
"""Computes all metrics for each timestamp in an individual run."""
price_sample = kwargs["price_sample"]
trade_data = kwargs["trade_data"]

prices = DataFrame(price_sample.prices.to_list(), index=price_sample.index)

Expand All @@ -104,7 +106,6 @@ def _compute_profits(self, price_df, trade_df):
Computes arbitrageur profits and pool fees for a single row of data (i.e.,
a single timestamp) in units of the chosen numeraire, `self.numeraire`.
"""
get_price = self.get_market_price
numeraire = self.numeraire

profit = []
Expand All @@ -115,14 +116,16 @@ def _compute_profits(self, price_df, trade_df):
pool_profit = 0

for trade in trade_row:
market_price = get_price(trade.coin_in, trade.coin_out, prices)
market_price = self.get_market_price(
trade.coin_in, trade.coin_out, prices
)
arb = trade.amount_out - trade.amount_in * market_price
fee = trade.fee

if trade.coin_out != numeraire:
price = get_price(trade.coin_out, numeraire, prices)
arb = arb * price
fee = fee * price
price = self.get_market_price(trade.coin_out, numeraire, prices)
arb *= price
fee *= price

arb_profit += arb
pool_profit += fee
Expand Down Expand Up @@ -177,21 +180,23 @@ def pool_config(self):

return config

def get_stableswap_pool_volume(self, trade_data, **kwargs):
def get_stableswap_pool_volume(self, **kwargs):
"""
Records trade volume for stableswap non-meta-pools.
"""
trade_data = kwargs["trade_data"]

def per_timestamp_function(trades):
return sum([trade.amount_in for trade in trades]) / 10**18
return sum(trade.amount_in for trade in trades) / 10**18

return self._get_volume(trade_data, per_timestamp_function)

def get_stableswap_metapool_volume(self, trade_data, **kwargs):
def get_stableswap_metapool_volume(self, **kwargs):
"""
Records trade volume for stableswap meta-pools. Only includes trades involving
the meta-asset (basepool-only trades are ignored).
"""
trade_data = kwargs["trade_data"]

meta_asset = self._pool.assets.symbols[0]

Expand Down Expand Up @@ -255,11 +260,12 @@ def pool_config(self):
[SimCurveMetaPool, SimCurvePool, SimCurveRaiPool], ss_config
)

def get_stableswap_balance(self, pool_state, **kwargs):
def get_stableswap_balance(self, **kwargs):
"""
Computes pool balance metrics for each timestamp in an individual run.
Used for any stableswap pool.
"""
pool_state = kwargs["pool_state"]
balance = pool_state.apply(self._compute_stableswap_balance, axis=1)
return DataFrame(balance, columns=["pool_balance"])

Expand All @@ -271,7 +277,7 @@ def _compute_stableswap_balance(self, pool_state_row):
self.set_pool_state(pool_state_row)
pool = self._pool

xp = array(pool._xp())
xp = array(pool._xp()) # pylint: disable=protected-access
n = pool.n
bal = 1 - sum(abs(xp / sum(xp) - 1 / n)) / (2 * (n - 1) / n)

Expand Down Expand Up @@ -344,11 +350,14 @@ def pool_config(self):
},
}

def get_stableswap_pool_value(self, pool_state, price_sample, **kwargs):
def get_stableswap_pool_value(self, **kwargs):
"""
Computes all metrics for each timestamp in an individual run.
Used for non-meta stableswap pools.
"""
pool_state = kwargs["pool_state"]
price_sample = kwargs["price_sample"]

reserves = DataFrame(
pool_state.balances.to_list(),
index=pool_state.index,
Expand All @@ -366,11 +375,14 @@ def get_stableswap_pool_value(self, pool_state, price_sample, **kwargs):
results.columns = list(self.config["plot"]["metrics"])
return results.astype("float64")

def get_stableswap_metapool_value(self, pool_state, price_sample, **kwargs):
def get_stableswap_metapool_value(self, **kwargs):
"""
Computes all metrics for each timestamp in an individual run.
Used for stableswap metapools.
"""
pool_state = kwargs["pool_state"]
price_sample = kwargs["price_sample"]

max_coin = self._pool.max_coin
pool = self._pool

Expand Down Expand Up @@ -471,13 +483,15 @@ def pool_config(self):

def __init__(self, pool, factor=10**8, **kwargs):
self._factor = factor
super().__init__(pool)
super().__init__(pool, **kwargs)

def get_curve_LD(self, pool_state, **kwargs):
def get_curve_LD(self, **kwargs):
"""
Computes liquidity density for each timestamp in an individual run.
Used for all Curve pools.
"""
pool_state = kwargs["pool_state"]

coin_pairs = get_pairs(
self._pool.coin_names
) # for metapool, uses only meta assets
Expand Down Expand Up @@ -538,5 +552,6 @@ class Timestamp(Metric):
def config(self):
return {"functions": {"metrics": self._get_timestamp}}

def _get_timestamp(self, price_sample, **kwargs):
def _get_timestamp(self, **kwargs):
price_sample = kwargs["price_sample"]
return DataFrame(price_sample.timestamp)
8 changes: 7 additions & 1 deletion curvesim/metrics/results/make_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ def make_results(data_per_run, data_per_trade, summary_data, metrics):
factors = get_factors(data_per_run)
plot_config = combine_plot_configs(metrics)

return SimResults(data_per_run, data_per_trade, summary_data, factors, plot_config)
return SimResults(
data_per_run=data_per_run,
data_per_trade=data_per_trade,
summary_data=summary_data,
factors=factors,
plot_config=plot_config,
)


def combine_plot_configs(metrics):
Expand Down
1 change: 1 addition & 0 deletions curvesim/metrics/results/sim_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class SimResults:

def __init__(
self,
*,
data_per_run,
data_per_trade,
summary_data,
Expand Down
Loading

0 comments on commit 2a6759d

Please sign in to comment.