Make marketsim support buying and selling via sign of shares
This commit is contained in:
@@ -75,16 +75,28 @@ def get_portfolio_value(holding, prices):
|
||||
def handle_order(date, order, holding, prices, commission, impact):
|
||||
"""Process the 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]
|
||||
cost = shares * adj_closing_price
|
||||
# Charge commission and deduct impact penalty
|
||||
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}")
|
||||
holding['cash'] -= cost
|
||||
holding[symbol] += shares
|
||||
elif order == "SELL":
|
||||
elif order.upper() == "SELL":
|
||||
# print(f"Sell {shares:6} of {symbol:4} on {date}")
|
||||
holding['cash'] += cost
|
||||
holding[symbol] -= shares
|
||||
|
||||
Reference in New Issue
Block a user