Browse Source

refactor: imports and comments

Signed-off-by: QuentinN42 <quentin@lieumont.fr>
pull/24/head
QuentinN42 6 months ago
parent
commit
7120faffb0
Signed by: number42 GPG Key ID: 2CD7D563712B3A50
  1. 20
      auto_trading/interfaces.py
  2. 22
      auto_trading/strat/Yoyo.py
  3. 27
      auto_trading/strat/yoyo.py
  4. 6
      main.py

20
auto_trading/interfaces.py

@ -6,10 +6,9 @@ import logging
from abc import ABC, abstractmethod, abstractproperty
from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List, Optional, Any, Callable
import pandas as pd
from pandas import DataFrame, Timedelta, Series # type: ignore
from typing import Dict, List, Optional, Any, Callable
from .errors import OrderException, UnknowOrder, PTFException
@ -28,7 +27,7 @@ class PTFState:
)
def to_dict(self):
return {'USD': self.balance, **self.stocks}
return {"USD": self.balance, **self.stocks}
@dataclass
@ -144,22 +143,25 @@ class Strategy(ABC):
class PTF(ABC):
"""Somethink that buy or sell stocks."""
executors: Dict[Any, Callable[[Any, Any], None]] = {}
orders_history: List[Order]
states_history: pd.DataFrame
states_history: DataFrame
def __init__(self, skip_errors: bool = True, save_errors: bool = True):
"""Init the class.
Args:
skip_errors (bool, optional): Do we skip orders in failure ? Defaults to True.
save_errors (bool, optional): Do we save orders in failure in the orders_history ? Defaults to True.
skip_errors (bool, optional): Do we skip orders in failure ?
Defaults to True.
save_errors (bool, optional): Do we save orders in failure in the orders_history ?
Defaults to True.
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.orders_history = []
self.states_history = pd.DataFrame()
self.states_history = DataFrame()
self.skip_errors = skip_errors
self.save_errors = save_errors
@ -195,7 +197,9 @@ class PTF(ABC):
if self.save_errors or order.successfull:
self.orders_history.append(order)
# self.states_history.append(self.state.to_dict(), ignore_index=True)
self.states_history = self.states_history.append(self.state.to_dict(), ignore_index=True)
self.states_history = self.states_history.append(
self.state.to_dict(), ignore_index=True
)
def _execute(self, order: Order) -> None:
"""Execute one order.

22
auto_trading/strat/Yoyo.py

@ -1,22 +0,0 @@
from auto_trading.interfaces import Strategy
from auto_trading.orders import Long, Short
class Yoyo(Strategy):
def __init__(self, stock_name: str):
super().__init__()
self.stock_name = stock_name
self.c = True
def execute(
self, data, indicators_results, ptf_state
):
market_price = data.loc[data.index[-1][0]].close.to_dict().get('GOOGL')
if self.c:
self.c = False
return [Long('GOOGL', 0.1, market_price)]
else:
self.c = True
return [Short('GOOGL', 0.1, market_price)]

27
auto_trading/strat/yoyo.py

@ -0,0 +1,27 @@
"""Yoyo strategy."""
from auto_trading.interfaces import Strategy
from auto_trading.orders import Long, Short
class Yoyo(Strategy):
"""A strat that buy a stock one time then sell it."""
def __init__(self, stock_name: str):
super().__init__()
self.stock_name = stock_name
self.buy = True
def execute(self, data, indicators_results, ptf_state):
market_price = data.loc[data.index[-1][0]].close.to_dict().get(self.stock_name)
if not market_price:
return []
if self.buy:
self.buy = False
todo = Long
else:
self.buy = True
todo = Short
return [todo(self.stock_name, 0.1, market_price)]

6
main.py

@ -6,7 +6,7 @@ from auto_trading.indicators.ema import EMA
from auto_trading.indicators.sma import SMA
from auto_trading.interfaces import Strategy
from auto_trading.orders import Long, Short
from auto_trading.strat.Yoyo import Yoyo
from auto_trading.strat.yoyo import Yoyo
from auto_trading.strat.hold import Hold
from auto_trading.ptf.in_memory import InMemoryPortfolio
from auto_trading.bot import Bot
@ -23,7 +23,7 @@ if __name__ == "__main__":
)
# strategy = Hold("GOOGL")
# strategy = Prop({"EMA": EMA(10)})
strategy = Yoyo('GOOGL')
strategy = Yoyo("GOOGL")
bot = Bot(ptf, strategy, bt)
@ -36,7 +36,7 @@ if __name__ == "__main__":
# plot the history
ch_history: pd.DataFrame = bot.broker.change_rate_history # type: ignore
ch_history['USD'] = 1
ch_history["USD"] = 1
st_history = bot.ptf.states_history
st_history.index = ch_history.index

Loading…
Cancel
Save