storage_client = storage.Client() bucket = storage_client.get_bucket('derek-algo-trading-bucket') blob = bucket.blob('alpaca-api-key.txt') api_key = blob.download_as_text() blob = bucket.blob('alpaca-secret-key.txt') secret_key = blob.download_as_text() base_url = 'https://paper-api.alpaca.markets' api = REST(api_key, secret_key, base_url, 'v2') # Check if the market is open today nyc = timezone('America/New_York') today = datetime.today().astimezone(nyc) today_str = today.strftime('%Y-%m-%d') today = datetime.isoformat(pd.Timestamp(datetime.today().astimezone(nyc))) try: calendar = api.get_calendar(start=today, end=today)[0] except Exception as e: print(e) print('Market must not be open') calendar = None if calendar and calendar.date.strftime('%Y-%m-%d') == today_str: # Select the swing stocks to buy, sell, and hold df_buy, df_sell, df_hold = select_swing_stocks() alert = f'**Daily Swing Trade Alert**\n' # Sell all stocks in DataFrame if not df_sell.empty: df_sell = df_sell.set_index('symbol', drop=True) print('\nSELLING:')
# Also need to store the results for each day day_results = {} # Create a list of dates in between start and end (inclusive) dates = pd.date_range(start=start_date, end=end_date, freq='B', tz=nyc) # Trade each day for date in dates: print( f'------------------ {date.strftime("%Y-%m-%d")} ------------------' ) # Check if market is open on that date calendar = api.get_calendar( start=datetime.isoformat(pd.Timestamp(date)), end=datetime.isoformat(pd.Timestamp(date)))[0] if calendar.date.strftime("%Y-%m-%d") != date.strftime("%Y-%m-%d"): print('Market was not open') print(calendar.date.strftime("%Y-%m-%d")) print(date.strftime("%Y-%m-%d")) continue # Must update position prices before going into the day # Something that Alpaca handles for you if len(position_data.keys()) > 0: for symbol in position_data.keys(): current_open_price = get_open_price(date, symbol) position_data[symbol]['current_price'] = str( current_open_price) position_data[symbol]['market_value'] = str(