Browse Source

Visualisation

master
Barthélemy Paléologue 8 months ago
parent
commit
0287aafa5e
  1. 33
      auto_trading/indicators/slopy.py
  2. 19
      auto_trading/strat/buyupselldown.py
  3. 26
      main.py

33
auto_trading/indicators/slopy.py

@ -25,35 +25,26 @@ class Slopy(Indicator):
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"))
highData = data2["close"]
# select only last two days
last2D = highData.last("2D")
lastND = 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]))
# lastND.rolling(window=2).mean()
ultieme = last2D[column].get(last2D.index[-1])
penultieme = last2D[column].get(last2D.index[-2])
res = {}
for column in lastND.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:
res[column] = 1

19
auto_trading/strat/buyupselldown.py

@ -9,10 +9,9 @@ from ..interfaces import Indicator, Strategy, Order, PTFState
class BuyUpSellDown(Strategy):
"""Just hold some stock."""
def __init__(self, to_hold: str, indicators: Dict[str, Indicator]):
def __init__(self, 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
@ -35,10 +34,12 @@ class BuyUpSellDown(Strategy):
orders = []
# if I have some money
for stock_name in indicators_results.columns:
#for each stock
# 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)
market_price = (
data.loc[data.index[-1][0]].close.to_dict().get(stock_name)
)
trust = int(indicators_results[stock_name])
print(trust)
@ -46,14 +47,18 @@ class BuyUpSellDown(Strategy):
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))
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))
orders.append(
Short(stock=stock_name, amount=amount, price=market_price)
)
return orders # type: ignore

26
main.py

@ -1,3 +1,6 @@
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
@ -9,19 +12,36 @@ from auto_trading.bot import Bot
if __name__ == "__main__":
bt = Backtest("./data/NYSE_smallest.csv")
bt = Backtest("./data/NYSE_small.csv")
ptf = InMemoryPortfolio(
base_balance=100, change_rate_getter=lambda: bt.current_change
)
#strategy = Hold("GOOGL", {"dumb": Dumb(bt.data.close)})
strategy = BuyUpSellDown("GOOGL", {"slopy": Slopy()})
# strategy = Hold("GOOGL", {"dumb": Dumb(bt.data.close)})
strategy = BuyUpSellDown({"slopy": Slopy()})
bot = Bot(ptf, strategy, bt)
bot.run()
###### Visualisation ######
data = bt.data.unstack()
# select high prices for each action
closeData = data["close"]
sma = closeData.rolling(window=5).mean()
ema = closeData.ewm(alpha=0.6).mean()
plt.plot(closeData, label="real", marker="x", linewidth=0)
plt.plot(sma, color="red", label="SMA")
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