prediction-market-agent-tooling 0.44.0__py3-none-any.whl → 0.45.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,11 @@ class LogConfig(BaseSettings):
31
31
  LOG_LEVEL: LogLevel = LogLevel.DEBUG
32
32
 
33
33
 
34
+ class NoNewLineStreamHandler(logging.StreamHandler): # type: ignore # StreamHandler is not typed in the standard library.
35
+ def format(self, record: logging.LogRecord) -> str:
36
+ return super().format(record).replace("\n", " ")
37
+
38
+
34
39
  GCP_LOG_LOGURU_FORMAT = (
35
40
  "{level:<.1}{time:MMDD HH:mm:ss} {process} {name}:{line}] {message}"
36
41
  )
@@ -40,6 +45,10 @@ GCP_LOG_LOGGING_FORMAT, GCP_LOG_FORMAT_LOGGING_DATEFMT = (
40
45
 
41
46
 
42
47
  def patch_logger() -> None:
48
+ """
49
+ Function to patch loggers according to the deployed environment.
50
+ Patches Loguru's logger, Python's default logger, warnings library and also monkey-patch print function as many libraries just use it.
51
+ """
43
52
  config = LogConfig()
44
53
 
45
54
  if config.LOG_FORMAT == LogFormat.GCP:
@@ -47,10 +56,12 @@ def patch_logger() -> None:
47
56
  format_logging = GCP_LOG_LOGGING_FORMAT
48
57
  datefmt_logging = GCP_LOG_FORMAT_LOGGING_DATEFMT
49
58
  print_logging = print_using_loguru_info
59
+ handlers = [NoNewLineStreamHandler()]
50
60
 
51
61
  elif config.LOG_FORMAT == LogFormat.DEFAULT:
52
62
  format_loguru, format_logging, datefmt_logging = None, None, None
53
63
  print_logging = None
64
+ handlers = None
54
65
 
55
66
  else:
56
67
  raise ValueError(f"Unknown log format: {config.LOG_FORMAT}")
@@ -58,7 +69,10 @@ def patch_logger() -> None:
58
69
  # Change built-in logging.
59
70
  if format_logging is not None:
60
71
  logging.basicConfig(
61
- level=config.LOG_LEVEL.value, format=format_logging, datefmt=datefmt_logging
72
+ level=config.LOG_LEVEL.value,
73
+ format=format_logging,
74
+ datefmt=datefmt_logging,
75
+ handlers=handlers,
62
76
  )
63
77
 
64
78
  # Change loguru.
@@ -1,110 +1,67 @@
1
- import typing as t
1
+ from enum import Enum
2
2
 
3
- from prediction_market_agent_tooling.gtypes import Probability, wei_type, xDai
4
- from prediction_market_agent_tooling.markets.omen.data_models import OmenMarket
5
- from prediction_market_agent_tooling.tools.utils import check_not_none
6
- from prediction_market_agent_tooling.tools.web3_utils import (
7
- ONE_XDAI,
8
- wei_to_xdai,
9
- xdai_to_wei,
10
- )
3
+ from pydantic import BaseModel
11
4
 
12
- OutcomeIndex = t.Literal[0, 1]
13
5
 
6
+ class BetDirection(str, Enum):
7
+ YES = "Yes"
8
+ NO = "No"
14
9
 
15
- def _get_kelly_criterion_bet(
16
- x: int, y: int, p: float, c: float, b: int, f: float
17
- ) -> int:
10
+
11
+ class KellyBet(BaseModel):
12
+ direction: BetDirection
13
+ size: float
14
+
15
+
16
+ def check_is_valid_probability(probability: float) -> None:
17
+ if not 0 <= probability <= 1:
18
+ raise ValueError("Probability must be between 0 and 1")
19
+
20
+
21
+ def get_kelly_bet(
22
+ max_bet: float,
23
+ market_p_yes: float,
24
+ estimated_p_yes: float,
25
+ confidence: float,
26
+ ) -> KellyBet:
18
27
  """
19
- Implments https://en.wikipedia.org/wiki/Kelly_criterion
20
-
21
- Taken from https://github.com/valory-xyz/trader/blob/main/strategies/kelly_criterion/kelly_criterion.py
22
-
23
- ```
24
- Licensed under the Apache License, Version 2.0 (the "License");
25
- you may not use this file except in compliance with the License.
26
- You may obtain a copy of the License at
27
-
28
- http://www.apache.org/licenses/LICENSE-2.0
29
-
30
- Unless required by applicable law or agreed to in writing, software
31
- distributed under the License is distributed on an "AS IS" BASIS,
32
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
- See the License for the specific language governing permissions and
34
- limitations under the License.
35
- ```
36
-
37
- x: Number of tokens in the selected outcome pool
38
- y: Number of tokens in the other outcome pool
39
- p: Probability of winning
40
- c: Confidence
41
- b: Bankroll
42
- f: Fee fraction
28
+ Calculate the optimal bet amount using the Kelly Criterion for a binary outcome market.
29
+
30
+ From https://en.wikipedia.org/wiki/Kelly_criterion:
31
+
32
+ f* = p - q / b
33
+
34
+ where:
35
+ - f* is the fraction of the current bankroll to wager
36
+ - p is the probability of a win
37
+ - q = 1-p is the probability of a loss
38
+ - b is the proportion of the bet gained with a win
39
+
40
+ Note: this calculation does not factor in that the bet changes the market
41
+ odds. This means the calculation is only accurate if the bet size is small
42
+ compared to the market volume. See discussion here for more detail:
43
+ https://github.com/gnosis/prediction-market-agent-tooling/pull/330#discussion_r1698269328
43
44
  """
44
- if b == 0:
45
- return 0
46
- numerator = (
47
- -4 * x**2 * y
48
- + b * y**2 * p * c * f
49
- + 2 * b * x * y * p * c * f
50
- + b * x**2 * p * c * f
51
- - 2 * b * y**2 * f
52
- - 2 * b * x * y * f
53
- + (
54
- (
55
- 4 * x**2 * y
56
- - b * y**2 * p * c * f
57
- - 2 * b * x * y * p * c * f
58
- - b * x**2 * p * c * f
59
- + 2 * b * y**2 * f
60
- + 2 * b * x * y * f
61
- )
62
- ** 2
63
- - (
64
- 4
65
- * (x**2 * f - y**2 * f)
66
- * (
67
- -4 * b * x * y**2 * p * c
68
- - 4 * b * x**2 * y * p * c
69
- + 4 * b * x * y**2
70
- )
71
- )
72
- )
73
- ** (1 / 2)
74
- )
75
- denominator = 2 * (x**2 * f - y**2 * f)
76
- if denominator == 0:
77
- return 0
78
- kelly_bet_amount = numerator / denominator
79
- return int(kelly_bet_amount)
80
-
81
-
82
- def get_kelly_criterion_bet(
83
- market: OmenMarket,
84
- estimated_p_yes: Probability,
85
- max_bet: xDai,
86
- ) -> t.Tuple[xDai, OutcomeIndex]:
87
- if len(market.outcomeTokenAmounts) != 2:
88
- raise ValueError("Only binary markets are supported.")
89
-
90
- current_p_yes = check_not_none(
91
- market.outcomeTokenProbabilities, "No probabilities, is marked closed?"
92
- )[0]
93
- outcome_index: OutcomeIndex = 0 if estimated_p_yes > current_p_yes else 1
94
- estimated_p_win = estimated_p_yes if outcome_index == 0 else 1 - estimated_p_yes
95
-
96
- kelly_bet_wei = wei_type(
97
- _get_kelly_criterion_bet(
98
- x=market.outcomeTokenAmounts[outcome_index],
99
- y=market.outcomeTokenAmounts[1 - outcome_index],
100
- p=estimated_p_win,
101
- c=1, # confidence
102
- b=xdai_to_wei(max_bet), # bankroll, or max bet, in Wei
103
- f=(
104
- xdai_to_wei(ONE_XDAI)
105
- - check_not_none(market.fee, "No fee for the market.")
106
- )
107
- / xdai_to_wei(ONE_XDAI), # fee fraction
108
- )
109
- )
110
- return wei_to_xdai(kelly_bet_wei), outcome_index
45
+ check_is_valid_probability(market_p_yes)
46
+ check_is_valid_probability(estimated_p_yes)
47
+ check_is_valid_probability(confidence)
48
+
49
+ if estimated_p_yes > market_p_yes:
50
+ bet_direction = BetDirection.YES
51
+ market_prob = market_p_yes
52
+ else:
53
+ bet_direction = BetDirection.NO
54
+ market_prob = 1 - market_p_yes
55
+
56
+ # Handle the case where market_prob is 0
57
+ if market_prob == 0:
58
+ market_prob = 1e-10
59
+
60
+ edge = abs(estimated_p_yes - market_p_yes) * confidence
61
+ odds = (1 / market_prob) - 1
62
+ kelly_fraction = edge / odds
63
+
64
+ # Ensure bet size is non-negative does not exceed the wallet balance
65
+ bet_size = min(kelly_fraction * max_bet, max_bet)
66
+
67
+ return KellyBet(direction=bet_direction, size=bet_size)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: prediction-market-agent-tooling
3
- Version: 0.44.0
3
+ Version: 0.45.1
4
4
  Summary: Tools to benchmark, deploy and monitor prediction market agents.
5
5
  Author: Gnosis
6
6
  Requires-Python: >=3.10,<3.12
@@ -22,7 +22,7 @@ prediction_market_agent_tooling/deploy/gcp/deploy.py,sha256=CYUgnfy-9XVk04kkxA_5
22
22
  prediction_market_agent_tooling/deploy/gcp/kubernetes_models.py,sha256=qYIHRxQLac3yxtZ8ChikiPG9O1aUQucHW0muTSm1nto,2627
23
23
  prediction_market_agent_tooling/deploy/gcp/utils.py,sha256=oyW0jgrUT2Tr49c7GlpcMsYNQjoCSOcWis3q-MmVAhU,6089
24
24
  prediction_market_agent_tooling/gtypes.py,sha256=ezM2iAycTRJ0uHKK03s0z76a8YFSF438kjOwT_BAqz4,2474
25
- prediction_market_agent_tooling/loggers.py,sha256=ua9rynYmsbOJZjxPIFxRBooomeN08zuLSJ7lxZMDS7w,3133
25
+ prediction_market_agent_tooling/loggers.py,sha256=JiBTgvb34O9dKHYKZyQ0UzojPUy6KSFQSTfbBIXopSY,3721
26
26
  prediction_market_agent_tooling/markets/agent_market.py,sha256=BELq6x3F4xLZwi0XmoN84RA7ttRQIclyHL2CY6a4Ixc,8409
27
27
  prediction_market_agent_tooling/markets/categorize.py,sha256=HyKSFHXPL7Hfe90ahbF7xszamYREUVrPkLcpifw1V9Y,935
28
28
  prediction_market_agent_tooling/markets/data_models.py,sha256=qD0LyFkzimaMkDVE0QO2a4I9fQ8qpO2qPmVzb-0JBik,2085
@@ -56,7 +56,7 @@ prediction_market_agent_tooling/monitor/monitor_app.py,sha256=THyZ67baByakoOm3hI
56
56
  prediction_market_agent_tooling/monitor/monitor_settings.py,sha256=Xiozs3AsufuJ04JOe1vjUri-IAMWHjjmc2ugGGiHNH4,947
57
57
  prediction_market_agent_tooling/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
58
58
  prediction_market_agent_tooling/tools/balances.py,sha256=nR8_dSfbm3yTOOmMAwhGlurftEiNo1w1WIVzbskjdmM,837
59
- prediction_market_agent_tooling/tools/betting_strategies/kelly_criterion.py,sha256=IbhQPoKsQnjnag_n_wAL12n8QdCe7tAMRNV2QS8yYxY,3520
59
+ prediction_market_agent_tooling/tools/betting_strategies/kelly_criterion.py,sha256=d3QEg1Bia8D7SPHGr-SgP0OHSLIzm_hf4sN4iz06qiM,1951
60
60
  prediction_market_agent_tooling/tools/betting_strategies/market_moving.py,sha256=wtrHVQRuA0uDx06z0OxQLYbswuOpHQ1UyCWwLCrD_oM,4400
61
61
  prediction_market_agent_tooling/tools/betting_strategies/minimum_bet_to_win.py,sha256=-FUSuQQgjcWSSnoFxnlAyTeilY6raJABJVM2QKkFqAY,438
62
62
  prediction_market_agent_tooling/tools/betting_strategies/stretch_bet_between.py,sha256=THMXwFlskvzbjnX_OiYtDSzI8XVFyULWfP2525_9UGc,429
@@ -75,8 +75,8 @@ prediction_market_agent_tooling/tools/singleton.py,sha256=CiIELUiI-OeS7U7eeHEt0r
75
75
  prediction_market_agent_tooling/tools/streamlit_user_login.py,sha256=NXEqfjT9Lc9QtliwSGRASIz1opjQ7Btme43H4qJbzgE,3010
76
76
  prediction_market_agent_tooling/tools/utils.py,sha256=JE9YWtPPhnTgLiOyGAZDNG5K8nCwUY9IZEuAlm9UcxA,6611
77
77
  prediction_market_agent_tooling/tools/web3_utils.py,sha256=nKRHmdLnWSKd3wpo-cysXGvhhrJ2Yf69sN2FFQfSt6s,10578
78
- prediction_market_agent_tooling-0.44.0.dist-info/LICENSE,sha256=6or154nLLU6bELzjh0mCreFjt0m2v72zLi3yHE0QbeE,7650
79
- prediction_market_agent_tooling-0.44.0.dist-info/METADATA,sha256=uEMgSr-fSEh1CWW385kM1dmHFcmhPX5u_BcLj0NETvM,7634
80
- prediction_market_agent_tooling-0.44.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
81
- prediction_market_agent_tooling-0.44.0.dist-info/entry_points.txt,sha256=m8PukHbeH5g0IAAmOf_1Ahm-sGAMdhSSRQmwtpmi2s8,81
82
- prediction_market_agent_tooling-0.44.0.dist-info/RECORD,,
78
+ prediction_market_agent_tooling-0.45.1.dist-info/LICENSE,sha256=6or154nLLU6bELzjh0mCreFjt0m2v72zLi3yHE0QbeE,7650
79
+ prediction_market_agent_tooling-0.45.1.dist-info/METADATA,sha256=cuop8gl4vJj_cojxAvKj9nQX4tDKPhxjIuahsc1CCX0,7634
80
+ prediction_market_agent_tooling-0.45.1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
81
+ prediction_market_agent_tooling-0.45.1.dist-info/entry_points.txt,sha256=m8PukHbeH5g0IAAmOf_1Ahm-sGAMdhSSRQmwtpmi2s8,81
82
+ prediction_market_agent_tooling-0.45.1.dist-info/RECORD,,