Browse Source

feat: current_change comes from broker

pull/14/head
QuentinN42 11 months ago
parent
commit
ea0e90986a
Signed by: number42 GPG Key ID: 2CD7D563712B3A50
  1. 12
      auto_trading/interfaces.py
  2. 2
      auto_trading/strat/hold.py
  3. 15
      tests/strat/test_hold.py

12
auto_trading/interfaces.py

@ -18,13 +18,11 @@ class PTFState:
balance: float
stocks: Dict[str, float]
conversion_rate: DataFrame
@property
def total_balance(self) -> float:
conv = self.conversion_rate.to_dict()
def total_balance(self, conversion_rate: Dict[str, float]) -> float:
return self.balance + sum(
conv[stock_name] * amount for stock_name, amount in self.stocks.items()
conversion_rate[stock_name] * amount
for stock_name, amount in self.stocks.items()
)
@ -161,6 +159,10 @@ class PTF(ABC):
"""Return the current total balance."""
return self.state.balance
def total_balance(self, conversion_rate: Dict[str, float]) -> float:
"""Return the current total balance."""
return self.state.total_balance(conversion_rate)
def execute_multiples(self, orders: List[Order]) -> None:
"""Execute all orders

2
auto_trading/strat/hold.py

@ -33,7 +33,7 @@ class Hold(Strategy):
# if I have some money
if (balance := state.balance) > 0:
# I calculate the value of the stock
market_price = state.conversion_rate.iloc[-1].to_dict()[self.to_hold]
market_price = data.iloc[-1].to_dict()[self.to_hold]
amount = balance / market_price
# and I buy it all at market price
orders.append(Long(stock=self.to_hold, amount=amount, price=market_price))

15
tests/strat/test_hold.py

@ -7,34 +7,35 @@ from auto_trading.orders import Long
@pytest.mark.parametrize(
"state, output",
"data, state, output",
[
(State(balance=0, stocks={}, conversion_rate=DataFrame()), None),
(DataFrame(), State(balance=0, stocks={}), None),
(
State(balance=10, stocks={}, conversion_rate=DataFrame({"AAPL": [10]})),
DataFrame({"AAPL": [10]}),
State(balance=10, stocks={}),
Long(stock="AAPL", amount=1, price=10),
),
(
DataFrame({"AAPL": [10]}),
State(
balance=10,
stocks={"AAPL": 5},
conversion_rate=DataFrame({"AAPL": [10]}),
),
Long(stock="AAPL", amount=1, price=10),
),
(
DataFrame({"AAPL": [10], "TSLA": [20]}),
State(
balance=10,
stocks={"AAPL": 5, "TSLA": 5},
conversion_rate=DataFrame({"AAPL": [10], "TSLA": [20]}),
),
Long(stock="AAPL", amount=1, price=10),
),
],
)
def test_hold(state, output):
def test_hold(data, state, output):
strat = Hold(to_hold="AAPL")
res = strat.execute(DataFrame(), DataFrame(), state)
res = strat.run(data, state)
if output is None:
assert len(res) == 0
else:

Loading…
Cancel
Save