Created
January 27, 2020 21:35
-
-
Save hsauers5/a7caa28f51019a4681399e1698336fce to your computer and use it in GitHub Desktop.
This file contains 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
import alpaca_trade_api | |
key = 'YOUR_KEY' | |
secret = 'YOUR_SECRET' | |
base_url = 'https://paper-api.alpaca.markets' | |
api = alpaca_trade_api.REST(key, secret, base_url, api_version='v2') | |
account = api.get_account() | |
print(account.status) | |
stock_list = ['AAPL', 'GOOG', 'MSN', 'INTC'] | |
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) | |
for stock in stock_list: | |
print(stock) | |
order_target_percent(api, stock, 0.05) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment