Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_tinkoff-contest-python-main/src/traders/base.py
5935 views
1
import abc
2
import importlib.util
3
import inspect
4
import sys
5
from typing import List, Type
6
7
from src.containers.config import TraderConfig
8
from src.containers.market import MarketState, TraderDecision
9
10
11
class BaseTrader(metaclass=abc.ABCMeta):
12
_trader_name: str = None
13
14
@classmethod
15
@property
16
def name(cls):
17
return cls._trader_name
18
19
def __init__(self, trader_config: TraderConfig):
20
self.trader_config = trader_config
21
22
def initial_message(self):
23
return f"Are you sure you want to start the {self.name} trader? (yes/no)"
24
25
@abc.abstractmethod
26
async def make_decisions(self, state: MarketState) -> List[TraderDecision]:
27
raise NotImplementedError
28
29
30
def load_trader_class(file_name) -> Type[BaseTrader]:
31
# find and load the file as a python module
32
module_name = f"traders.{file_name}"
33
spec = importlib.util.spec_from_file_location(module_name, f"src/traders/{file_name}.py")
34
module = importlib.util.module_from_spec(spec)
35
sys.modules[module_name] = module
36
spec.loader.exec_module(module)
37
38
# find the trader class in the module
39
module_classes = inspect.getmembers(module, inspect.isclass)
40
trader_cls = next(
41
class_
42
for _, class_ in module_classes
43
if hasattr(class_, "_trader_name") and class_ is not BaseTrader and issubclass(class_, BaseTrader)
44
)
45
return trader_cls
46
47