Created
January 27, 2020 21:27
-
-
Save hsauers5/f623617f2ba6f33a0b702da37e3979c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def order_target_percent(api, security, weight, order_type='market', time_in_force='day'): | |
account = api.get_account() | |
portfolio_value = float(account.portfolio_value) | |
current_holdings = 0 | |
try: | |
current_holdings = api.get_position(security).qty | |
except alpaca_trade_api.rest.APIError: | |
current_holdings = 0 | |
stock_price = api.get_barset(security, "minute", limit=2)[security][-1].c | |
current_weight = (current_holdings * stock_price) / portfolio_value | |
weight = weight - current_weight | |
side = 'buy' if weight > 0 else 'sell' | |
quantity = int((portfolio_value * abs(weight)) / stock_price) | |
api.submit_order(security, quantity, side, order_type, time_in_force) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment