Skip to content

Commit

Permalink
feat: Make sure the cash balance does not fall below zero
Browse files Browse the repository at this point in the history
  • Loading branch information
suminb committed Nov 1, 2023
1 parent cc49849 commit 976e163
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions finance/ext/warehouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,14 @@ def apply_plan(
):
def apply(t, q):
self.inventory.setdefault(t, 0)
while self.inventory["_USD"] - self.current_prices[t] * q < 0:
if q > 0:
q -= 1
else:
q += 1
self.inventory["_USD"] -= self.current_prices[t] * q
if self.inventory["_USD"] < 0:
raise ValueError(f"USD balance cannot be negative: {t}, {q}")
return self.inventory[t] + q

# 'close' is actually 'adj close', which already includes dividends/stock split/capital gains
Expand All @@ -382,5 +389,4 @@ def calc_dividends_sum(
if q < 0:
raise ValueError(f"Quantity cannot be negative: {t}, {q}")
div_sum += div_amount * q
# print(f"div[{t}] = {div_amount} * {q} = {div_amount * q}, {start_dt}, {end_dt}")
return div_sum
return div_sum

0 comments on commit 976e163

Please sign in to comment.