Make marketsim support buying and selling via sign of shares

This commit is contained in:
2020-10-27 19:53:55 -04:00
parent 85a9c4fcb3
commit 1798e9569e

View File

@@ -75,16 +75,28 @@ def get_portfolio_value(holding, prices):
def handle_order(date, order, holding, prices, commission, impact): def handle_order(date, order, holding, prices, commission, impact):
"""Process the order.""" """Process the order."""
symbol, order, shares = order symbol, order, shares = order
assert(shares > 0) # Can only buy or sell positive amount of shares. if shares == 0 and order == "":
return # empty order
if pd.isnull(shares):
return # shares is nan
# Allow indicating buying and selling via shares. If shares is positive we
# buy and if it is negative we sell.
if shares > 0 and order == "":
order = "BUY"
elif shares < 0 and order == "":
order = "SELL"
shares = abs(shares)
adj_closing_price = prices[symbol] adj_closing_price = prices[symbol]
cost = shares * adj_closing_price cost = shares * adj_closing_price
# Charge commission and deduct impact penalty # Charge commission and deduct impact penalty
holding['cash'] -= (commission + impact * adj_closing_price * shares) holding['cash'] -= (commission + impact * adj_closing_price * shares)
if order == "BUY": if order.upper() == "BUY":
# print(f"Buy {shares:6} of {symbol:4} on {date}") # print(f"Buy {shares:6} of {symbol:4} on {date}")
holding['cash'] -= cost holding['cash'] -= cost
holding[symbol] += shares holding[symbol] += shares
elif order == "SELL": elif order.upper() == "SELL":
# print(f"Sell {shares:6} of {symbol:4} on {date}") # print(f"Sell {shares:6} of {symbol:4} on {date}")
holding['cash'] += cost holding['cash'] += cost
holding[symbol] -= shares holding[symbol] -= shares