Browse Source

La strat peut supporter plusieurs indicateurs

master
Barthélemy Paléologue 8 months ago
parent
commit
aaabf49715
  1. 57
      auto_trading/indicators/sma.py
  2. 18
      auto_trading/strat/buyupselldown.py
  3. 7
      main.py

57
auto_trading/indicators/sma.py

@ -0,0 +1,57 @@
"""SMA indicator, for testing purposes."""
from calendar import c
from re import sub
import pandas as pd # type: ignore
from ..interfaces import Indicator
class SMA(Indicator):
"""Replay the value."""
def __init__(self, windowSize: int):
"""Save the value."""
super().__init__()
self.windowSize = windowSize
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"]
# lastND.rolling(window=2).mean()
sma = data3.rolling(window=self.windowSize).mean()
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
return pd.Series(res)

18
auto_trading/strat/buyupselldown.py

@ -38,15 +38,21 @@ class BuyUpSellDown(Strategy):
# 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])
### compute trust
trust = 0
for (index, row) in indicators_results.iterrows():
if row[stock_name] > 0:
trust += 1
elif row[stock_name] < 0:
trust -= 1
print(trust)
if market_price is None:
# retry later
return []
continue
if trust > 0:
if (balance := state.balance) > 0:
amount = balance / (market_price * nb_stock_type)
# and I buy it all at market price
@ -54,13 +60,9 @@ class BuyUpSellDown(Strategy):
Long(stock=stock_name, amount=amount, price=market_price)
)
else:
# I don't have money
orders
# print("A PU DE THUNE")
print("A PU DE THUNE")
elif trust < 0:
# and I sell it all at market price
orders
# print(state.stocks)
orders.append(
Short(
stock=stock_name,

7
main.py

@ -1,9 +1,9 @@
from matplotlib import lines
import matplotlib.pyplot as plt
from auto_trading.broker.backtest import Backtest
from auto_trading.indicators.dumb import Dumb
from auto_trading.indicators.slopy import Slopy
from auto_trading.indicators.sma import SMA
from auto_trading.interfaces import Indicator
from auto_trading.strat.buyupselldown import BuyUpSellDown
from auto_trading.strat.hold import Hold
@ -17,8 +17,7 @@ if __name__ == "__main__":
base_balance=100, change_rate_getter=lambda: bt.current_change
)
# strategy = Hold("GOOGL", {"dumb": Dumb(bt.data.close)})
strategy = BuyUpSellDown({"slopy": Slopy()})
strategy = BuyUpSellDown({"slopy": Slopy(), "sma": SMA(windowSize=5)})
bot = Bot(ptf, strategy, bt)
@ -42,8 +41,6 @@ if __name__ == "__main__":
for order in ptf.history:
print(order)
# plt.plot(bot.balance_history, label="balance")
print(bot.ptf.total_balance(bot.broker.current_change))
plt.show()

Loading…
Cancel
Save