Skip to content

Commit

Permalink
chore: refactor and clean
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidMinarsch committed Nov 18, 2023
1 parent e109827 commit 1303887
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 37 deletions.
10 changes: 5 additions & 5 deletions packages/packages.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"dev": {
"skill/valory/market_manager_abci/0.1.0": "bafybeigesvgfjjtzxnsofhwutsp4pyclxnn62z2luy4xt7yarm64u6pbti",
"skill/valory/decision_maker_abci/0.1.0": "bafybeihgb4hxrlfviop5keq37wt6a4se4crxgldzkyyagvtfunurlrj7vu",
"skill/valory/trader_abci/0.1.0": "bafybeiawfnk2t3t2vc2rxuwywdpwnixwcl35xpwibvnc6uj2kkrm3fiosu",
"skill/valory/decision_maker_abci/0.1.0": "bafybeiczcpdknyev4mzp72un4lre6tmddpbagju7ecwbmtsbjemmr5d2x4",
"skill/valory/trader_abci/0.1.0": "bafybeialxshboebcgs5ucgi5upu6y4vrkgnbbx3oyaynwgjk74vmpcyqnu",
"contract/valory/market_maker/0.1.0": "bafybeih4r35d3plsjw56ham6xvi6dn4semmuihc53lh3qofpwj242rnjkq",
"agent/valory/trader/0.1.0": "bafybeif767jocewxohmknjf2fhqnryds327r74stjg5ykqw3jtolibifoi",
"service/valory/trader/0.1.0": "bafybeic44fdusoljstyptuopnpbqzptyebuvdojze77gj7q6nsqpb4pihy",
"agent/valory/trader/0.1.0": "bafybeihnjel5x4rs6fptwz5g2d5prwanuwvb4ntlxtsunsgg64rkuc6u3u",
"service/valory/trader/0.1.0": "bafybeid3jvs6dkkln3t7xfngn6zguqs6whsx5jodqkqtic7zbg2guadfp4",
"contract/valory/erc20/0.1.0": "bafybeidpjppgs7jlig2gdpdr3a6q3etbejpxrifjhzlcufpo5zf23dqv7y",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeieg23bd2fj5xaelys5uz2iggdx7zdxv2vnzfgfw7ndipw5b4so3xe",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeiagiyzwolc3hc5gt3wuzvgfqdh25e5wi4jbouq2rsb67twgopucnm",
"contract/valory/mech/0.1.0": "bafybeigjn4q6mxal2hxzjyzldl4t4aykkpxjnbsgnli2c3xwf6binkmn74",
"contract/valory/realitio/0.1.0": "bafybeiamgkwwqhray4fs2hlipwxkq7mosmi7ev7jut4vneetaaycc4ruji",
"contract/valory/realitio_proxy/0.1.0": "bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4",
Expand Down
6 changes: 3 additions & 3 deletions packages/valory/agents/trader/aea-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ skills:
- valory/reset_pause_abci:0.1.0:bafybeiflxcl2dtzayyzzddc4f2astzxunyp66meutornanrgeemicdea5q
- valory/termination_abci:0.1.0:bafybeifazwrksp756h7z42qqfcgi6lya6wmhbx46l7ghlaooe45gqnju7q
- valory/transaction_settlement_abci:0.1.0:bafybeigxkdujugzvve2dszkwr5kgfx4uhz2epofo4lorbcnthmzfjegwzi
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeieg23bd2fj5xaelys5uz2iggdx7zdxv2vnzfgfw7ndipw5b4so3xe
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeiagiyzwolc3hc5gt3wuzvgfqdh25e5wi4jbouq2rsb67twgopucnm
- valory/market_manager_abci:0.1.0:bafybeigesvgfjjtzxnsofhwutsp4pyclxnn62z2luy4xt7yarm64u6pbti
- valory/decision_maker_abci:0.1.0:bafybeihgb4hxrlfviop5keq37wt6a4se4crxgldzkyyagvtfunurlrj7vu
- valory/trader_abci:0.1.0:bafybeiawfnk2t3t2vc2rxuwywdpwnixwcl35xpwibvnc6uj2kkrm3fiosu
- valory/decision_maker_abci:0.1.0:bafybeiczcpdknyev4mzp72un4lre6tmddpbagju7ecwbmtsbjemmr5d2x4
- valory/trader_abci:0.1.0:bafybeialxshboebcgs5ucgi5upu6y4vrkgnbbx3oyaynwgjk74vmpcyqnu
- valory/staking_abci:0.1.0:bafybeifoejd5q6wgmqohhwp46uwk3g4ysr7f5mf2fbmjhxulwzwdy2udui
default_ledger: ethereum
required_ledgers:
Expand Down
2 changes: 1 addition & 1 deletion packages/valory/services/trader/service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license: Apache-2.0
fingerprint:
README.md: bafybeigtuothskwyvrhfosps2bu6suauycolj67dpuxqvnicdrdu7yhtvq
fingerprint_ignore_patterns: []
agent: valory/trader:0.1.0:bafybeif767jocewxohmknjf2fhqnryds327r74stjg5ykqw3jtolibifoi
agent: valory/trader:0.1.0:bafybeihnjel5x4rs6fptwz5g2d5prwanuwvb4ntlxtsunsgg64rkuc6u3u
number_of_agents: 4
deployment: {}
---
Expand Down
23 changes: 7 additions & 16 deletions packages/valory/skills/decision_maker_abci/behaviours/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"""This module contains the base behaviour for the 'decision_maker_abci' skill."""

import dataclasses
import random
from abc import ABC
from datetime import datetime, timedelta
from typing import Any, Callable, Generator, List, Optional, cast
Expand All @@ -43,6 +42,7 @@
from packages.valory.skills.decision_maker_abci.models import (
DecisionMakerParams,
MultisendBatch,
STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD,
SharedState,
)
from packages.valory.skills.decision_maker_abci.policy import EGreedyPolicy
Expand Down Expand Up @@ -72,22 +72,12 @@ def remove_fraction_wei(amount: int, fraction: float) -> int:
raise ValueError(f"The given fraction {fraction!r} is not in the range [0, 1].")


def perturb_y_if_x_equals_y(x: int, y: int) -> float:
"""Introduce perturbation to the y value if x equals y."""
epsilon = (x + y) / 10000
y += epsilon if random.choice([True, False]) else -epsilon # nosec
return y


def calculate_kelly_bet_amount(
x: int, y: int, p: float, c: float, b: int, f: float
) -> int:
"""Calculate the Kelly bet amount."""
if b == 0:
return 0
if x == y:
# o/w kelly traders will never be the first to bet in a new market
y = perturb_y_if_x_equals_y(x, y)
numerator = (
-4 * x**2 * y
+ b * y**2 * p * c * f
Expand Down Expand Up @@ -117,7 +107,7 @@ def calculate_kelly_bet_amount(
)
** (1 / 2)
)
denominator = (2 * (x**2 * f - y**2 * f))
denominator = 2 * (x**2 * f - y**2 * f)
kelly_bet_amount = numerator / denominator
return int(kelly_bet_amount)

Expand Down Expand Up @@ -304,17 +294,18 @@ def get_bet_amount(
) -> Generator[None, None, int]:
"""Get the bet amount given a specified trading strategy."""

if strategy == "bet_amount_per_conf_threshold":
# Kelly Criterion does not trade for equally weighted pools.
if (
strategy == STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD
or selected_type_tokens_in_pool == other_tokens_in_pool
):
self.context.logger.info(
"Used trading strategy: Bet amount per confidence threshold"
)
threshold = round(confidence, 1)
bet_amount = self.params.bet_amount_per_threshold[threshold]
return bet_amount

if strategy != "kelly_criterion":
raise ValueError(f"Invalid trading strategy: {strategy}")

self.context.logger.info("Used trading strategy: Kelly Criterion")
# bankroll: the max amount of DAI available to trade
yield from self.wait_for_condition_with_sleep(self.check_balance)
Expand Down
11 changes: 10 additions & 1 deletion packages/valory/skills/decision_maker_abci/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
DEFAULT_FROM_BLOCK = "earliest"
ZERO_HEX = HASH_ZERO[2:]
ZERO_BYTES = bytes.fromhex(ZERO_HEX)
STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD = "bet_amount_per_conf_threshold"
STRATEGY_KELLY_CRITERION = "kelly_criterion"


class PromptTemplate(Template):
Expand Down Expand Up @@ -178,6 +180,13 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:

# the trading strategy to use for placing bets
self.trading_strategy: str = self._ensure("trading_strategy", kwargs, str)
if self.trading_strategy not in [
STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD,
STRATEGY_KELLY_CRITERION,
]:
raise ValueError(
f"The trading strategy {self.trading_strategy} is not supported!"
)
# the factor of calculated kelly bet to use for placing bets
self.bet_kelly_fraction: float = self._ensure(
"bet_kelly_fraction", kwargs, float
Expand Down Expand Up @@ -235,7 +244,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
@property
def using_kelly(self) -> bool:
"""Get the max bet amount if the `bet_amount_per_conf_threshold` strategy is used."""
return self.trading_strategy == "kelly_criterion"
return self.trading_strategy == STRATEGY_KELLY_CRITERION

@property
def max_bet_amount(self) -> int:
Expand Down
6 changes: 3 additions & 3 deletions packages/valory/skills/decision_maker_abci/skill.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fingerprint:
README.md: bafybeia367zzdwndvlhw27rvnwodytjo3ms7gbc3q7mhrrjqjgfasnk47i
__init__.py: bafybeih563ujnigeci2ldzh7hakbau6a222vsed7leg3b7lq32vcn3nm4a
behaviours/__init__.py: bafybeih6ddz2ocvm6x6ytvlbcz6oi4snb5ee5xh5h65nq4w2qf7fd7zfky
behaviours/base.py: bafybeigjneci2qmj5odhey3vuwc6g5stes4aqoly2ks3owrxe2a2rcco7e
behaviours/base.py: bafybeifwz5zbbaia4q4oll6cldtvt47w2hw2qadptkmmtovmitzgpizyki
behaviours/bet_placement.py: bafybeigtz4uimsqjjwq4r5p3a5v6niqdtqezbuf2ghy6o7syhsh4k5gjfa
behaviours/blacklisting.py: bafybeicl6b4hcmqmekta2mcuhkkydnzk7jmic6k44e6ns3u2ibad3awzvu
behaviours/decision_receive.py: bafybeifacce2ke7oltnwnpdjdqfd74eaaw5wxnjfzk6c5tqdsxsmbzjj3m
Expand All @@ -25,7 +25,7 @@ fingerprint:
dialogues.py: bafybeigpwuzku3we7axmxeamg7vn656maww6emuztau5pg3ebsoquyfdqm
fsm_specification.yaml: bafybeifnob3ceim2mj7lqagtnpwqjqqxs5eg3oiwc73gwm6x5i2dvvlcya
handlers.py: bafybeihj33szgrcxnpd73s4nvluyxwwsvhjum2cuq3ilhhe6vfola3k7vy
models.py: bafybeifskab7b3nqalkenjgk745ky4h7bsqar73zzvrnygymhjl4qxl2ga
models.py: bafybeifvohs24ddh5lujdx6rgmulzoovs3dmmsza3vieugstq3idv2iday
payloads.py: bafybeifhq6stu4vp2ef4qvihxgpos3yc2zcuaja2safwt7efdidoejgvqa
policy.py: bafybeidpmx4ek3qze63zpuwixyf6t7bdv62ewgkzt3ljrzadiwdw64cueq
redeem_info.py: bafybeibddfxwp3577c3dl2utaowwltquu5fg6crezpumoebw563wxpbfrm
Expand All @@ -43,7 +43,7 @@ fingerprint:
states/tool_selection.py: bafybeiaaijv6dukp3bmsptcwkcmumc6wu6ztzkvaqzsqqjbfn4ozgyuykq
tests/__init__.py: bafybeiakpi3k3kc7wrjj7hrluvjcj36lu2gezpmrctwiz5yg2fe7ggnf3i
tests/conftest.py: bafybeic2xlujtbkyqk2zzpo5vorefwa3nwgfwmrk5rx77vu4gfyrn3pv5m
tests/test_behaviours.py: bafybeibmnf2w4s27fjk6qdjbnmci3xeoh7xwaxlhmffed4mtf42minsqky
tests/test_behaviours.py: bafybeigfrzuqlxok7zmkyjd4t2p6wovmenx7n3zo7xu5jprv46jkzp2kqa
fingerprint_ignore_patterns: []
connections: []
contracts:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@

"""This module contains the tests for valory/decision_maker_abci's behaviours."""

from packages.valory.skills.decision_maker_abci.tests.conftest import profile_name
from packages.valory.skills.decision_maker_abci.behaviours.base import calculate_kelly_bet_amount

from hypothesis import given, settings
from hypothesis import strategies as st

from packages.valory.skills.decision_maker_abci.behaviours.base import (
calculate_kelly_bet_amount,
)
from packages.valory.skills.decision_maker_abci.tests.conftest import profile_name


settings.load_profile(profile_name)

Expand All @@ -39,5 +41,6 @@
)
def test_calculate_kelly_bet_amount(
x: int, y: int, p: float, c: float, b: int, f: float
):
assert calculate_kelly_bet_amount(x, y, p, c, b, f) >= -10
) -> None:
"""Test the calculate_kelly_bet_amount function."""
assert calculate_kelly_bet_amount(x, y, p, c, b, f) >= -10
4 changes: 2 additions & 2 deletions packages/valory/skills/trader_abci/skill.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ skills:
- valory/transaction_settlement_abci:0.1.0:bafybeigxkdujugzvve2dszkwr5kgfx4uhz2epofo4lorbcnthmzfjegwzi
- valory/termination_abci:0.1.0:bafybeifazwrksp756h7z42qqfcgi6lya6wmhbx46l7ghlaooe45gqnju7q
- valory/market_manager_abci:0.1.0:bafybeigesvgfjjtzxnsofhwutsp4pyclxnn62z2luy4xt7yarm64u6pbti
- valory/decision_maker_abci:0.1.0:bafybeihgb4hxrlfviop5keq37wt6a4se4crxgldzkyyagvtfunurlrj7vu
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeieg23bd2fj5xaelys5uz2iggdx7zdxv2vnzfgfw7ndipw5b4so3xe
- valory/decision_maker_abci:0.1.0:bafybeiczcpdknyev4mzp72un4lre6tmddpbagju7ecwbmtsbjemmr5d2x4
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeiagiyzwolc3hc5gt3wuzvgfqdh25e5wi4jbouq2rsb67twgopucnm
- valory/staking_abci:0.1.0:bafybeifoejd5q6wgmqohhwp46uwk3g4ysr7f5mf2fbmjhxulwzwdy2udui
behaviours:
main:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ protocols:
- valory/ledger_api:1.0.0:bafybeige5agrztgzfevyglf7mb4o7pzfttmq4f6zi765y4g2zvftbyowru
skills:
- valory/abstract_round_abci:0.1.0:bafybeigrqhygo2hl2owisj5rqyh3acdvee773ajije64snlzalcgtaac7q
- valory/decision_maker_abci:0.1.0:bafybeihgb4hxrlfviop5keq37wt6a4se4crxgldzkyyagvtfunurlrj7vu
- valory/decision_maker_abci:0.1.0:bafybeiczcpdknyev4mzp72un4lre6tmddpbagju7ecwbmtsbjemmr5d2x4
- valory/staking_abci:0.1.0:bafybeifoejd5q6wgmqohhwp46uwk3g4ysr7f5mf2fbmjhxulwzwdy2udui
behaviours:
main:
Expand Down

0 comments on commit 1303887

Please sign in to comment.