Browse Source

feat: working yoyo

Signed-off-by: QuentinN42 <quentin@lieumont.fr>
pull/24/head
QuentinN42 7 months ago
parent
commit
19e699fd6f
Signed by: number42 GPG Key ID: 2CD7D563712B3A50
  1. 4
      auto_trading/ptf/in_memory.py
  2. 45
      auto_trading/strat/yoyo.py

4
auto_trading/ptf/in_memory.py

@ -1,4 +1,4 @@
from typing import Dict, Callable, List
from typing import Dict, Callable
from ..interfaces import PTF, PTFState
from ..orders import Long, Short
@ -33,7 +33,7 @@ class InMemoryPortfolio(PTF):
def execute_short(self, order: Short) -> None:
"""Sell actions."""
if self._stocks[order.stock] < order.amount:
if (self._stocks.get(order.stock) or 0) < order.amount:
raise OrderFails("Not enough stock.")
if self.change_rate.get(order.stock, 0) < order.price:
raise OrderFails("You shell it too high.")

45
auto_trading/strat/yoyo.py

@ -1,6 +1,19 @@
"""Yoyo strategy."""
from auto_trading.interfaces import Strategy
from auto_trading.interfaces import Strategy, Order, PTFState
from auto_trading.orders import Long, Short
from typing import List, Dict, cast, Callable
import pandas as pd # type: ignore
def is_positive(number: float | None) -> bool:
"""Return True if the price is positive."""
return number is not None and number > 0
def as_stocks(stocks: Dict[str, float]) -> bool:
"""Check if we currently have some stocks to sell."""
return any(map(is_positive, stocks.values()))
class Yoyo(Strategy):
@ -12,16 +25,32 @@ class Yoyo(Strategy):
self.stock_name = stock_name
self.buy = True
def execute(self, data, indicators_results, ptf_state):
def execute(
self,
data: pd.DataFrame,
indicators_results: pd.DataFrame,
ptf_state: PTFState,
) -> List[Order]:
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
todo: Callable[[PTFState, float], Order]
if as_stocks(ptf_state.stocks):
todo = self.create_buy_order
else:
self.buy = True
todo = Short
todo = self.create_sell_order
return [todo(ptf_state, market_price)]
def create_sell_order(self, ptf: PTFState, current_price: float) -> Order:
"""Create a sell order."""
return cast(
Order, Long(self.stock_name, ptf.balance / current_price, current_price)
)
def create_buy_order(self, ptf: PTFState, current_price: float) -> Order:
"""Create a buy order."""
return [todo(self.stock_name, 0.1, market_price)]
return cast(
Order, Short(self.stock_name, ptf.stocks[self.stock_name], current_price)
)

Loading…
Cancel
Save