Skip to content

Commit

Permalink
Td 1 (#48)
Browse files Browse the repository at this point in the history
* upd
  • Loading branch information
m5l14i11 authored Sep 9, 2024
1 parent 571d825 commit 72f462c
Show file tree
Hide file tree
Showing 16 changed files with 79 additions and 82 deletions.
13 changes: 9 additions & 4 deletions copilot/_actor.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import asyncio
import logging
import re
from typing import Union

import numpy as np
from core.models.strategy_type import StrategyType
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA, KernelPCA
Expand All @@ -25,11 +25,14 @@
from core.models.risk_type import SessionRiskType, SignalRiskType
from core.models.side import PositionSide, SignalSide
from core.models.signal_risk import SignalRisk
from core.models.strategy_type import StrategyType
from core.queries.copilot import EvaluateSession, EvaluateSignal

from ._prompt import (
signal_contrarian_risk_prompt,
signal_risk_pattern,
signal_trend_risk_prompt,
system_prompt,
)

CopilotEvent = Union[EvaluateSignal, EvaluateSession]
Expand Down Expand Up @@ -127,8 +130,6 @@ def _init_centroids(self, X, random_state):


class CopilotActor(BaseActor, EventHandlerMixin):
_EVENTS = [EvaluateSignal, EvaluateSession]

def __init__(self, llm: AbstractLLMService):
super().__init__()
EventHandlerMixin.__init__(self)
Expand Down Expand Up @@ -171,7 +172,11 @@ async def _evaluate_signal(self, msg: EvaluateSignal) -> SignalRisk:
)

bar = sorted(prev_bar + [curr_bar], key=lambda x: x.timestamp)
strategy_type = StrategyType.CONTRARIAN if "SUP" not in str(signal.strategy) else StrategyType.TREND_FOLLOW
strategy_type = (
StrategyType.CONTRARIAN
if "SUP" not in str(signal.strategy)
else StrategyType.TREND_FOLLOW
)

template = (
signal_contrarian_risk_prompt
Expand Down
23 changes: 21 additions & 2 deletions core/actors/_base_actor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import inspect
import uuid
from typing import Union, get_args, get_origin

from core.commands.base import Command
from core.interfaces.abstract_actor import AbstractActor, Ask, Message
Expand All @@ -7,13 +9,12 @@


class BaseActor(AbstractActor):
_EVENTS = []

def __init__(self):
super().__init__()
self._running = False
self._mailbox = EventDispatcher()
self._id = str(uuid.uuid4())
self._EVENTS = self._discover_events()

@property
def id(self):
Expand Down Expand Up @@ -67,3 +68,21 @@ def _register_events(self):
def _unregister_events(self):
for event in self._EVENTS:
self._mailbox.unregister(event, self.on_receive)

def _discover_events(self):
sig = inspect.signature(self.on_receive)
params = list(sig.parameters.values())

if len(params) < 1:
return []

event_type = params[0].annotation

events = []

if get_origin(event_type) is Union:
events = get_args(event_type)
else:
events = [event_type]

return list(set(events))
2 changes: 0 additions & 2 deletions core/actors/_strategy_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@


class StrategyActor(BaseActor):
_EVENTS = []

def __init__(self, symbol: Symbol, timeframe: Timeframe):
super().__init__()
self._symbol = symbol
Expand Down
2 changes: 1 addition & 1 deletion core/events/position.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class BrokerPositionOpened(PositionEvent):


@dataclass(frozen=True)
class BrokerPositionAdjusted(PositionEvent):
class BrokerPositionReduced(PositionEvent):
pass


Expand Down
6 changes: 2 additions & 4 deletions core/models/strategy_type.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@


from enum import Enum, auto
from enum import Enum


class StrategyType(Enum):
TREND_FOLLOW = "Trend Follow"
CONTRARIAN = "Contrarian"

def __str__(self):
return self.value
return self.value
10 changes: 10 additions & 0 deletions core/queries/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import List

from core.events.base import EventMeta
from core.models.position import Position
from core.models.symbol import Symbol

from .base import Query, QueryGroup
Expand All @@ -22,3 +23,12 @@ class GetSymbol(Query[Symbol]):
default_factory=lambda: EventMeta(priority=3, group=QueryGroup.broker),
init=False,
)


@dataclass(frozen=True)
class HasPosition(Query[bool]):
position: Position
meta: EventMeta = field(
default_factory=lambda: EventMeta(priority=3, group=QueryGroup.broker),
init=False,
)
6 changes: 3 additions & 3 deletions executor/_market_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from core.mixins import EventHandlerMixin
from core.models.symbol import Symbol
from core.models.timeframe import Timeframe
from core.queries.broker import HasPosition
from core.queries.position import GetClosePosition, GetOpenPosition

logger = logging.getLogger(__name__)
Expand All @@ -21,8 +22,6 @@


class MarketOrderActor(StrategyActor, EventHandlerMixin):
_EVENTS = [PositionInitialized, PositionCloseRequested]

def __init__(self, symbol: Symbol, timeframe: Timeframe):
super().__init__(symbol, timeframe)
EventHandlerMixin.__init__(self)
Expand Down Expand Up @@ -58,7 +57,8 @@ async def _close_position(self, event: PositionCloseRequested):

logger.debug(f"To Close Position: {current_position}")

await self.ask(ClosePosition(current_position))
while await self.ask(HasPosition(current_position)):
await self.ask(ClosePosition(current_position))

order = await self.ask(GetClosePosition(current_position))

Expand Down
5 changes: 0 additions & 5 deletions executor/_paper_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,6 @@ class PriceDirection(Enum):


class PaperOrderActor(StrategyActor, EventHandlerMixin):
_EVENTS = [
PositionInitialized,
PositionCloseRequested,
]

def __init__(self, symbol: Symbol, timeframe: Timeframe):
super().__init__(symbol, timeframe)
EventHandlerMixin.__init__(self)
Expand Down
2 changes: 0 additions & 2 deletions feed/_historical.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ def _next_item_or_end(self):


class HistoricalActor(StrategyActor):
_EVENTS = [StartHistoricalFeed]

def __init__(
self,
symbol: Symbol,
Expand Down
2 changes: 0 additions & 2 deletions feed/_realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ async def __anext__(self):


class RealtimeActor(StrategyActor):
_EVENTS = [StartRealtimeFeed]

def __init__(
self,
symbol: Symbol,
Expand Down
2 changes: 0 additions & 2 deletions market/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@


class MarketActor(BaseActor, EventHandlerMixin):
_EVENTS = [NextBar, PrevBar, TA, BackNBars]

def __init__(self, ts: AbstractTimeSeriesService):
super().__init__()
EventHandlerMixin.__init__(self)
Expand Down
16 changes: 5 additions & 11 deletions position/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,6 @@


class PositionActor(StrategyActor):
_EVENTS = [
GoLongSignalReceived,
GoShortSignalReceived,
BrokerPositionOpened,
BrokerPositionClosed,
RiskThresholdBreached,
BacktestEnded,
]

def __init__(
self,
symbol: Symbol,
Expand All @@ -69,7 +60,7 @@ def __init__(
self.state = PositionStorage()
self.config = config_service.get("position")

async def on_receive(self, event):
async def on_receive(self, event: PositionEvent):
symbol, _ = self._get_event_key(event)

if hasattr(event, "position"):
Expand Down Expand Up @@ -103,7 +94,10 @@ async def create_and_store_position(event: SignalEvent):
EvaluateSignal(event.signal, back_bars, ta)
)

if signal_risk_level.type in {SignalRiskType.VERY_HIGH}:
if signal_risk_level.type in {
SignalRiskType.UNKNOWN,
SignalRiskType.VERY_HIGH,
}:
return False

position = await self.position_factory.create(
Expand Down
10 changes: 0 additions & 10 deletions position/_sm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from core.events.backtest import BacktestEnded
from core.events.position import (
BrokerPositionAdjusted,
BrokerPositionClosed,
BrokerPositionOpened,
)
Expand All @@ -29,7 +28,6 @@ class PositionState(Enum):

PositionEvent = Union[
BrokerPositionOpened,
BrokerPositionAdjusted,
BrokerPositionClosed,
GoLongSignalReceived,
GoShortSignalReceived,
Expand Down Expand Up @@ -57,10 +55,6 @@ class PositionState(Enum):
PositionState.CLOSE,
"handle_backtest",
),
(PositionState.OPENED, BrokerPositionAdjusted): (
PositionState.OPENED,
"handle_position_adjusted",
),
(PositionState.OPENED, RiskThresholdBreached): (
PositionState.CLOSE,
"handle_exit_received",
Expand Down Expand Up @@ -92,10 +86,6 @@ class PositionState(Enum):
PositionState.CLOSE,
"handle_backtest",
),
(PositionState.OPENED, BrokerPositionAdjusted): (
PositionState.OPENED,
"handle_position_adjusted",
),
(PositionState.OPENED, RiskThresholdBreached): (
PositionState.CLOSE,
"handle_exit_received",
Expand Down
10 changes: 0 additions & 10 deletions risk/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,6 @@ def _ema(values, alpha=0.1):


class RiskActor(StrategyActor, EventHandlerMixin):
_EVENTS = [
NewMarketDataReceived,
PositionOpened,
PositionClosed,
ExitLongSignalReceived,
ExitShortSignalReceived,
GoLongSignalReceived,
GoShortSignalReceived,
]

def __init__(
self, symbol: Symbol, timeframe: Timeframe, config_service: AbstractConfig
):
Expand Down
Loading

0 comments on commit 72f462c

Please sign in to comment.