Using datetime.now().strftime(‘%Y-%m-%d’) as my end_date and running the code after market close, but most recent data is from prior day. My trading signals generate at market close and curious to know when is the earliest I can run my code where it will include the current day’s data.
Or will I simply have to upgrade to the Real-Time API for this feature? Thanks
def fetch_alpaca_data(symbols, timeframe, start_date, end_date):
"""
Fetch stock bars data from Alpaca Markets based on the given timeframe for multiple symbols.
"""
url = 'https://data.alpaca.markets/v2/stocks/bars'
headers = {
'APCA-API-KEY-ID': API_KEY_ID,
'APCA-API-SECRET-KEY': API_SECRET_KEY
}
params = {
'symbols': '', # Placeholder for symbol
'timeframe': timeframe,
'start': '',
'end': '',
'limit': 10000,
'adjustment': 'raw',
'feed': 'sip'
}
data_list = []
eastern = pytz.timezone('America/New_York')
utc = pytz.utc
market_open = time(9, 30) # Market opens at 9:30 AM
market_close = time(15, 59) # Market closes just before 4:00 PM
for symbol in symbols:
print(f"Starting data fetch for symbol: {symbol}...")
# Update params #for each symbol
params['symbols'] = symbol
params['start'] = datetime.strptime(start_date, "%Y-%m-%d").isoformat() + 'Z'
params['end'] = datetime.strptime(end_date, "%Y-%m-%d").isoformat() + 'Z'
while True:
#print(f"Fetching data for symbol: {symbol} from {start_date} to {end_date}")
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
print(f"Error fetching data with status code {response.status_code}: {response.text}")
break
data = response.json()
bars = data.get('bars')
for symbol, entries in bars.items():
#print(f"Processing {len(entries)} entries for symbol: {symbol}")
for entry in entries:
try:
utc_time = datetime.fromisoformat(entry['t'].rstrip('Z')).replace(tzinfo=utc)
eastern_time = utc_time.astimezone(eastern)
# Apply market hours filter for '1Min' timeframe
if timeframe == '1Min' and not (market_open <= eastern_time.time() <= market_close):
continue # Skip entries outside market hours
data_entry = {
'symbol': symbol,
'volume': entry['v'],
'open': entry['o'],
'high': entry['h'],
'low': entry['l'],
'close': entry['c'],
'caldt': eastern_time
}
data_list.append(data_entry)
#print(f"Appended data for {symbol} at {eastern_time}")
except Exception as e:
print(f"Error processing entry: {entry}, {e}")
continue
if 'next_page_token' in data and data['next_page_token']:
params['page_token'] = data['next_page_token']
print("Fetching next page...")
else:
print("No more pages to fetch for symbol:", symbol)
break
df = pd.DataFrame(data_list)
print("Data fetching complete.")
return df