Been working on getting multiple symbols close data into dataframes however I’m stuck and could use a few pointers.
Currently my code is
import AlpacaConnect as ac
import alpaca as tradeapi
import pandas as pd
from alpaca.data.timeframe import TimeFrame
from alpaca.data.requests import StockBarsRequest
from alpaca.data.historical import StockHistoricalDataClient# Create stock historical data client
client = StockHistoricalDataClient(ac.Key, ac.SKey)
# Begin data
tickers_list = ['BP', 'XOM']
data = pd.DataFrame(columns=tickers_list)
# Set the start time
startTime = pd.to_datetime("2023-01-01").tz_localize('America/New_York')
endTime = pd.to_datetime("2024-01-01").tz_localize('America/New_York')
""" This doesn't work even though it looks like it should
for ticker in tickers_list:
tickerData= StockBarsRequest(symbol_or_symbols= ticker, timeframe=TimeFrame.Day, start=startTime, end=endTime)
data[ticker] = client.get_stock_bars(tickerData)
print(data[ticker].head())
"""
dataBP = StockBarsRequest(symbol_or_symbols= 'BP',timeframe=TimeFrame.Day, start=startTime, end=endTime)
dataXOM = StockBarsRequest(symbol_or_symbols= 'XOM',timeframe=TimeFrame.Day, start=startTime, end=endTime)
bpBars = client.get_stock_bars(dataBP)
xomBars = client.get_stock_bars(dataXOM)
bpDF = bpBars.df
xomDF = xomBars.df
bpClose = bpDF.loc[:, ["close"]]
xomClose = xomDF.loc[:, ["close"]]
print(bpClose.head())
print(xomClose.head())
which is mostly working except the result comes back in form
close
symbol timestamp
BP 2023-01-03 05:00:00+00:00 34.32
2023-01-04 05:00:00+00:00 33.78
2023-01-05 05:00:00+00:00 33.90
2023-01-06 05:00:00+00:00 34.46
2023-01-09 05:00:00+00:00 34.77
close
symbol timestamp
XOM 2023-01-03 05:00:00+00:00 106.51
2023-01-04 05:00:00+00:00 106.82
2023-01-05 05:00:00+00:00 109.21
2023-01-06 05:00:00+00:00 110.53
2023-01-09 05:00:00+00:00 108.47
and for the life of me I can’t figure out how to remove the date and timestamp because pandas seems convinced it’s part of the ‘close’ column
Lastly if anyone can tell me why the for ticker in tickers_list loop doesn’t work I’d really appreciate it. I’d like to write code that’s more modular however I haven’t figured out how to get this to loop like it would in yfinance