Browse Source

Test BuyUpSellDown

master
Barthélemy Paléologue 7 months ago
parent
commit
2e5fc638b0
  1. 25
      auto_trading/indicators/ema2.py
  2. 6
      auto_trading/indicators/sma2.py
  3. 23
      auto_trading/strat/buyupselldown.py
  4. 2
      main.py
  5. 36
      tests/indicators/test_ema2.py
  6. 85
      tests/strat/test_buyUpSellDown.py

25
auto_trading/indicators/ema2.py

@ -1,4 +1,6 @@
"""EMA indicator, not ready yet."""
import logging
import pandas as pd # type: ignore
from ..interfaces import Indicator
@ -26,24 +28,19 @@ class EMA(Indicator):
data2 = data.unstack()
# select high prices for each action
data3 = data2["close"]
# apply sma
ema = data3.ewm(alpha=self.alpha).mean()
data3 = data2.get("close")
if data3 is None:
return pd.Series([])
# computes slope at each point of the sma
emaDiff = ema.diff()
res = {}
for column in ema.columns:
# pour chaque type d'action
logging.info(data3)
coeff = emaDiff[column].get(ema.index[-1])
# apply ema
ema = data3.ewm(alpha=self.alpha).mean().fillna(0)
# TODO: ne pas hardcoder
normalization_factor = 0.2
trust = coeff * normalization_factor
# computes slope at each point of the sma
emaDiff = ema.diff().fillna(0)
res[column] = trust
res = emaDiff.iloc[-1]
return pd.Series(res)

6
auto_trading/indicators/sma2.py

@ -27,7 +27,9 @@ class SMA(Indicator):
data2 = data.unstack()
# select high prices for each action
data3 = data2["close"]
data3 = data2.get("close")
if data3 is None or len(data3[0]) == 0:
return pd.Series([])
# apply sma
sma = data3.rolling(window=self.windowSize).mean().fillna(0)
@ -36,6 +38,6 @@ class SMA(Indicator):
smaDiff = sma.diff().fillna(0)
res = smaDiff.iloc[-1]
logging.info(res)
#logging.info(res)
return pd.Series(res)

23
auto_trading/strat/buyupselldown.py

@ -1,17 +1,24 @@
from typing import Dict, List
import logging
from typing import List
import pandas as pd # type: ignore
from ..indicators.ema2 import EMA
from ..indicators.sma2 import SMA
from ..orders import Long, Short
from ..interfaces import Indicator, Strategy, Order, PTFState
from ..interfaces import Strategy, Order, PTFState
class BuyUpSellDown(Strategy):
"""Buy when indicators are green, sell when red."""
def __init__(self, indicators: Dict[str, Indicator]):
def __init__(self):
"""Init the class"""
super().__init__(indicators=indicators)
super().__init__()
self.indicators = {
"ema": EMA(alpha=0.6),
"sma": SMA(windowSize=5)
}
def execute(
self, data: pd.DataFrame, indicators_results: pd.DataFrame, state: PTFState
@ -42,7 +49,8 @@ class BuyUpSellDown(Strategy):
trust = 0
for (index, row) in indicators_results.iterrows():
trust += row[stock_name]
#print(trust)
#logging.info(indicators_results.get("AAPL"))
if market_price is None:
# retry later
@ -64,9 +72,10 @@ class BuyUpSellDown(Strategy):
orders.append(
Short(
stock=stock_name,
amount=state.stocks.get(stock_name),
amount=state.stocks[stock_name],
price=market_price,
)
)
# print(state.stocks)
#logging.info(orders)
return orders

2
main.py

@ -20,7 +20,7 @@ if __name__ == "__main__":
base_balance=100, change_rate_getter=lambda: bt.current_change
)
strategy = BuyUpSellDown({"ema": EMA(alpha=0.6), "sma": SMA(windowSize=5)})
strategy = BuyUpSellDown()
bot = Bot(ptf, strategy, bt)

36
tests/indicators/test_ema2.py

@ -0,0 +1,36 @@
"""Realy basic tests."""
import pytest
from datetime import datetime
from pandas import DataFrame, Series # type: ignore
from auto_trading.indicators.ema2 import EMA
def date(j: int) -> datetime:
return datetime.strptime(f"2015-03-{j}", "%Y-%m-%d")
@pytest.mark.parametrize(
"nb_values, data, expected",
[
(
10,
DataFrame(
{
"close": {
(date(i), st): 10 if i == 10 and st == "GOOG" else 0
for i in range(1, 11)
for st in ("GOOG", "GOOGL")
}
}
),
{"GOOG": 5.0, "GOOGL": 0.0},
),
],
)
def test_ema(nb_values: int, data: DataFrame, expected: Series) -> None:
"""Test the SMA indicator."""
ema = EMA(0.5)
res = {k: round(v, 2) for k, v in ema(data).to_dict().items()}
assert res == expected

85
tests/strat/test_buyUpSellDown.py

@ -0,0 +1,85 @@
"""Realy basic tests."""
import logging
from auto_trading.strat.buyupselldown import BuyUpSellDown
import pytest
from datetime import datetime, timedelta
from pandas import DataFrame, Series # type: ignore
from auto_trading.interfaces import PTFState as State
from auto_trading.orders import Long, Short
date = datetime.strptime("2015-03-31", "%Y-%m-%d")
@pytest.mark.parametrize(
"data, state, output",
[
(DataFrame(), State(balance=0, stocks={}), []),
(
DataFrame({"close": {(date, "AAPL"): []}}),
State(balance=10, stocks={}),
[],
),
(
DataFrame({"close": {(date, "AAPL"): 10}}),
State(balance=10, stocks={}),
[],
),
(
DataFrame({"close": {(date, "AAPL"): 10}}),
State(
balance=10,
stocks={"AAPL": 5},
),
[],
),
(
DataFrame({"close": {(date, "AAPL"): 10, (date, "TSLA"): 10}}),
State(
balance=10,
stocks={"AAPL": 5, "TSLA": 5},
),
[],
),
(
DataFrame({
"close": {
(date, "AAPL"): 5,
(date, "TSLA"): 10,
(date.today() + timedelta(days=1), "AAPL"): 20,
(date.today() + timedelta(days=1), "TSLA"): 5,
(date.today() + timedelta(days=2), "AAPL"): 30,
(date.today() + timedelta(days=2), "TSLA"): 4,
(date.today() + timedelta(days=3), "AAPL"): 40,
(date.today() + timedelta(days=3), "TSLA"): 2,
(date.today() + timedelta(days=4), "AAPL"): 50,
(date.today() + timedelta(days=4), "TSLA"): 1,
(date.today() + timedelta(days=5), "AAPL"): 70,
(date.today() + timedelta(days=5), "TSLA"): 1,
(date.today() + timedelta(days=6), "AAPL"): 100,
(date.today() + timedelta(days=6), "TSLA"): 1,
}
}),
State(
balance=100,
stocks={},
),
[],
),
],
)
def test_hold(data, state, output):
strat = BuyUpSellDown()
res = strat.run(data, state)
logging.info(res)
assert len(res) == len(output)
assert res == output
Loading…
Cancel
Save