Browse Source

Meilleurs indicateurs

- Amélioration de SMA : calcul de la dérivée localement au lieu de prendre la tendance sur les deux derniers jours
- Ajout d'un EMA basé sur le même principe
- Simplification de Slopy pour également utiliser la dérivée
- Le Bot utilise EMA et SMA et n'utilise plus Slopy
master
Barthélemy Paléologue 7 months ago
parent
commit
899fe0ab38
  1. 58
      auto_trading/indicators/ema2.py
  2. 29
      auto_trading/indicators/slopy.py
  3. 33
      auto_trading/indicators/sma2.py
  4. 4
      auto_trading/strat/buyupselldown.py
  5. 8
      main.py

58
auto_trading/indicators/ema2.py

@ -0,0 +1,58 @@
"""SMA indicator, not ready yet."""
from calendar import c
from re import sub
import pandas as pd # type: ignore
from ..interfaces import Indicator
class EMA(Indicator):
"""Replay the value."""
def __init__(self, alpha: int):
"""Save the value."""
super().__init__()
self.alpha = alpha
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.
"""
# only use date as index => actions become columns
data2 = data.unstack()
# select high prices for each action
data3 = data2["close"]
# apply sma
ema = data3.ewm(alpha=self.alpha).mean()
# computes slope at each point of the sma
emaDiff = ema.diff()
res = {}
for column in ema.columns:
# pour chaque type d'action
# print(column)
coeff = emaDiff[column].get(ema.index[-1])
# print(
# f"Coeff directeur : {coeff}\n Ultieme {ultieme}\n Penultieme {penultieme}"
# )
# TODO: ne pas hardcoder
trust = 1 + (coeff / 5)
trust = min(trust, 1.0)
trust = max(trust, 0.0)
res[column] = trust
print(trust)
return pd.Series(res)

29
auto_trading/indicators/slopy.py

@ -31,28 +31,19 @@ class Slopy(Indicator):
# select high prices for each action
highData = data2["close"]
# select only last two days
lastND = highData.last("2D")
# lastND.rolling(window=2).mean()
coeffs = highData.diff()
res = {}
for column in lastND.columns:
for column in coeffs.columns:
# pour chaque type d'action
# print(column)
if len(lastND.index) > 1:
# print(last2D[column].get(last2D.index[-1]), last2D[column].get(last2D.index[-2]))
ultieme = lastND[column].get(lastND.index[-1])
penultieme = lastND[column].get(lastND.index[-2])
if ultieme / penultieme > 1.05:
res[column] = 1
elif ultieme / penultieme < 0.95:
res[column] = -1
else:
res[column] = 0
else:
res[column] = 1
coeff = coeffs[column].get(coeffs.index[-1])
# TODO: ne pas hardcoder
trust = 1 + (coeff / 5)
trust = min(trust, 1.0)
trust = max(trust, 0.0)
res[column] = trust
return pd.Series(res)

33
auto_trading/indicators/sma2.py

@ -30,26 +30,29 @@ class SMA(Indicator):
# select high prices for each action
data3 = data2["close"]
# lastND.rolling(window=2).mean()
# apply sma
sma = data3.rolling(window=self.windowSize).mean()
# computes slope at each point of the sma
smaDiff = sma.diff()
res = {}
for column in sma.columns:
# pour chaque type d'action
# print(column)
if len(sma.index) > 1:
# print(last2D[column].get(last2D.index[-1]), last2D[column].get(last2D.index[-2]))
ultieme = sma[column].get(sma.index[-1])
penultieme = sma[column].get(sma.index[-2])
if ultieme / penultieme > 1.05:
res[column] = 1
elif ultieme / penultieme < 0.95:
res[column] = -1
else:
res[column] = 0
else:
res[column] = 1
coeff = smaDiff[column].get(sma.index[-1])
# print(
# f"Coeff directeur : {coeff}\n Ultieme {ultieme}\n Penultieme {penultieme}"
# )
# TODO: ne pas hardcoder
trust = 1 + (coeff / 5)
trust = min(trust, 1.0)
trust = max(trust, 0.0)
res[column] = trust
print(trust)
return pd.Series(res)

4
auto_trading/strat/buyupselldown.py

@ -45,7 +45,7 @@ class BuyUpSellDown(Strategy):
trust += 1
elif row[stock_name] < 0:
trust -= 1
print(trust)
# print(trust)
if market_price is None:
# retry later
@ -70,5 +70,5 @@ class BuyUpSellDown(Strategy):
price=market_price,
)
)
print(state.stocks)
# print(state.stocks)
return orders

8
main.py

@ -4,6 +4,7 @@ import logging
from auto_trading.broker.backtest import Backtest
from auto_trading.indicators.dumb import Dumb
from auto_trading.indicators.ema2 import EMA
from auto_trading.indicators.slopy import Slopy
from auto_trading.indicators.sma2 import SMA
from auto_trading.interfaces import Indicator
@ -14,7 +15,7 @@ from auto_trading.bot import Bot
pd.options.plotting.backend = "plotly"
logging.basicConfig(level=logging.DEBUG)
# logging.basicConfig(level=logging.INFO)
if __name__ == "__main__":
@ -23,7 +24,7 @@ if __name__ == "__main__":
base_balance=100, change_rate_getter=lambda: bt.current_change
)
strategy = BuyUpSellDown({"slopy": Slopy(), "sma": SMA(windowSize=5)})
strategy = BuyUpSellDown({"ema": EMA(alpha=0.6), "sma": SMA(windowSize=5)})
bot = Bot(ptf, strategy, bt)
@ -44,9 +45,6 @@ if __name__ == "__main__":
plt.plot(ema, color="green", label="EMA")
plt.legend()
# for order in ptf.history:
# print(order)
print(bot.ptf.total_balance(bot.broker.current_change))
plt.show()

Loading…
Cancel
Save