Browse Source

Ajout d'une strat et d'un indicateur

- La strat c'est simple : si ça monte sur les deux derniers jours, on achète sinon on vend
- L'indicateur calcule cette "dérivée" naive
- Beaucoup d'argent
thibaudlabat-spread
Barthélemy Paléologue 8 months ago
parent
commit
7d3a70f0b3
  1. 1
      auto_trading/indicators/dumb.py
  2. 65
      auto_trading/indicators/slopy.py
  3. 59
      auto_trading/strat/buyupselldown.py
  4. 8
      auto_trading/strat/hold.py
  5. 8
      main.py

1
auto_trading/indicators/dumb.py

@ -9,6 +9,7 @@ class Dumb(Indicator):
def __init__(self, value: pd.Series):
"""Save the value."""
#value c'est juste des settings qu'on veut
super().__init__()
self.value = value

65
auto_trading/indicators/slopy.py

@ -0,0 +1,65 @@
"""Dumb indicator, for testing purposes."""
from calendar import c
from re import sub
import pandas as pd # type: ignore
from ..interfaces import Indicator
class Slopy(Indicator):
"""Replay the value."""
def __init__(self):
"""Save the value."""
super().__init__()
def __call__(self, data: pd.DataFrame) -> pd.Series:
"""Return a dataframe of valuation of each stock from the input data.
Args:
data (DataFrame): Time-Stock valuated candlestick data.
For each time and each stock give (high, low, open, close).
Returns:
DataFrame: Stock valuated float.
For each stock give -1 if realy bad and +1 if realy good.
"""
#print(data.tail())
#print(data.index.names)
#print(data["date"])
#subdata = data["high"]
# only use date as index => actions become columns
data2 = data.unstack()
# select high prices for each action
highData = data2["high"]
#print(highData.tail())
#print(highData.last("2D"))
# select only last two days
last2D = highData.last("2D")
res = {}
for column in last2D.columns:
#pour chaque type d'action
#print(column)
if len(last2D.index) > 1:
#print(last2D[column].get(last2D.index[-1]), last2D[column].get(last2D.index[-2]))
ultieme = last2D[column].get(last2D.index[-1])
penultieme = last2D[column].get(last2D.index[-2])
if ultieme > penultieme:
res[column] = 1
else:
res[column] = -1
else:
res[column] = 1
return pd.Series(res)

59
auto_trading/strat/buyupselldown.py

@ -0,0 +1,59 @@
from typing import Dict, List
import pandas as pd # type: ignore
from ..orders import Long, Short
from ..interfaces import Indicator, Strategy, Order, PTFState
class BuyUpSellDown(Strategy):
"""Just hold some stock."""
def __init__(self, to_hold: str, indicators: Dict[str, Indicator]):
"""Init the class"""
super().__init__(indicators=indicators)
self.to_hold = to_hold
def execute(
self, data: pd.DataFrame, indicators_results: pd.DataFrame, state: PTFState
) -> List[Order]:
"""Just hold the value [to_hold].
Args:
data (DataFrame): The Data broker output.
For each time and each stock give (high, low, open, close).
indicators_results (DataFrame): Indicator-Stock valuated float.
For each indicator and each stock give -1 if realy bad and +1 if realy good.
Returns:
List[Order]: A list of orders to execute.
"""
nb_stock_type = len(indicators_results.columns)
orders = []
# if I have some money
for stock_name in indicators_results.columns:
#for each stock
if (balance := state.balance) > 0:
# I calculate the value of the stock
market_price = data.loc[data.index[-1][0]].close.to_dict().get(stock_name)
trust = int(indicators_results[stock_name])
print(trust)
if market_price is None:
# retry later
return []
amount = balance / (market_price * nb_stock_type)
if trust > 0:
# and I buy it all at market price
orders.append(Long(stock=stock_name, amount=amount, price=market_price))
elif trust < 0:
# and I sell it all at market price
orders.append(Short(stock=stock_name, amount=amount, price=market_price))
return orders # type: ignore

8
auto_trading/strat/hold.py

@ -1,17 +1,17 @@
from typing import List
from typing import Dict, List
import pandas as pd # type: ignore
from ..orders import Long
from ..interfaces import Strategy, Order, PTFState
from ..interfaces import Indicator, Strategy, Order, PTFState
class Hold(Strategy):
"""Just hold some stock."""
def __init__(self, to_hold: str):
def __init__(self, to_hold: str, indicators: Dict[str, Indicator]):
"""Init the class"""
super().__init__()
super().__init__(indicators=indicators)
self.to_hold = to_hold
def execute(

8
main.py

@ -1,4 +1,8 @@
from auto_trading.broker.backtest import Backtest
from auto_trading.indicators.dumb import Dumb
from auto_trading.indicators.slopy import Slopy
from auto_trading.interfaces import Indicator
from auto_trading.strat.buyupselldown import BuyUpSellDown
from auto_trading.strat.hold import Hold
from auto_trading.ptf.in_memory import InMemoryPortfolio
from auto_trading.bot import Bot
@ -9,7 +13,9 @@ if __name__ == "__main__":
ptf = InMemoryPortfolio(
base_balance=100, change_rate_getter=lambda: bt.current_change
)
strategy = Hold("GOOGL")
#strategy = Hold("GOOGL", {"dumb": Dumb(bt.data.close)})
strategy = BuyUpSellDown("GOOGL", {"slopy": Slopy()})
bot = Bot(ptf, strategy, bt)

Loading…
Cancel
Save