Im trying to run this cell:
import sys
import os
sys.path.append(os.path.abspath('..'))
import pandas as pd
from src.data_collector import fetch_historical_data
symbols = ['AAPL', 'MSFT', 'GOOGL']
historical_data = fetch_historical_data(symbols, '2023-01-01', '2024-01-01')
for symbol, df in historical_data.items():
df.to_csv(f'C:path/{symbol.lower()}.csv', index=False)
And I’m getting this error:
HTTPError Traceback (most recent call last)Cell In[2], line 85 from src.data_collector import fetch_historical_data7 symbols = ['AAPL', 'MSFT', 'GOOGL']----> 8 historical_data = fetch_historical_data(symbols, '2023-01-01', '2024-01-01')9 for symbol, df in historical_data.items():10 df.to_csv(f'C:path/{symbol.lower()}.csv', index=False)
File ~C:pathsrcdata_collector.py:26, in fetch_historical_data(symbols, start_date, end_date)24 with concurrent.futures.ThreadPoolExecutor() as executor:25 futures = [executor.submit(fetch_symbol_data, symbol, start_date, end_date) for symbol in symbols]---> 26 results = {future.result()[0]: future.result()[1] for future in concurrent.futures.as_completed(futures)}27 return results
File C:Program FilesLibconcurrentfutures_base.py:449, in Future.result(self, timeout)447 raise CancelledError()448 elif self._state == FINISHED:--> 449 return self.__get_result()451 self._condition.wait(timeout)453 if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
File C:Program FilesLibconcurrentfutures_base.py:401, in Future.__get_result(self)399 if self._exception:400 try:--> 401 raise self._exception402 finally:403 # Break a reference cycle with the exception in self._exception404 self = None
File C:Program FilesLibconcurrentfuturesthread.py:58, in _WorkItem.run(self)55 return57 try:---> 58 result = self.fn(*self.args, **self.kwargs)59 except BaseException as exc:60 self.future.set_exception(exc)
File ~C:pathsrcdata_collector.py:12, in fetch_symbol_data(symbol, start_date, end_date)10 def fetch_symbol_data(symbol, start_date, end_date):11 api = tradeapi.REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, BASE_URL, api_version='v2')---> 12 bars = api.get_bars(symbol, tradeapi.TimeFrame.Day, start=start_date, end=end_date).df13 data = [{14 'time': bar.Index.isoformat(),15 'open': bar.open,(...)19 'volume': bar.volume20 } for bar in bars.itertuples()]21 return symbol, pd.DataFrame(data)
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:735, in REST.get_bars(self, symbol, timeframe, start, end, adjustment, limit, feed, asof, sort)724 def get_bars(self,725 symbol: Union[str, List[str]],726 timeframe: TimeFrame,(...)733 sort: Optional[Sort] = None,734 ) -> BarsV2:--> 735 bars = list(self.get_bars_iter(symbol,736 timeframe,737 start,738 end,739 adjustment,740 limit,741 feed=feed,742 asof=asof,743 sort=sort,744 raw=True))745 return BarsV2(bars)
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:718, in REST.get_bars_iter(self, symbol, timeframe, start, end, adjustment, limit, feed, asof, sort, raw)697 def get_bars_iter(self,698 symbol: Union[str, List[str]],699 timeframe: TimeFrame,(...)706 sort: Optional[Sort] = None,707 raw=False) -> BarIterator:708 bars = self._data_get('bars', symbol,709 timeframe=timeframe,710 adjustment=adjustment,(...)716 sort=sort,717 )--> 718 for bar in bars:719 if raw:720 yield bar
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:594, in REST._data_get(self, endpoint, symbol_or_symbols, api_version, endpoint_base, resp_grouped_by_symbol, page_limit, feed, asof, loc, **kwargs)592 if endpoint:593 path += f'/{endpoint}'--> 594 resp = self.data_get(path, data=data, feed=feed,595 api_version=api_version)596 if not resp_grouped_by_symbol:597 k = endpoint or endpoint_base
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:274, in REST.data_get(self, path, data, feed, api_version)272 data = data or {}273 data['feed'] = feed--> 274 return self._request(275 'GET', path, data, base_url=base_url, api_version=api_version,276 )
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:222, in REST._request(self, method, path, data, base_url, api_version)220 while retry >= 0:221 try:--> 222 return self._one_request(method, url, opts, retry)223 except RetryException:224 retry_wait = self._retry_wait
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:248, in REST._one_request(self, method, url, opts, retry)246 if resp.status_code in retry_codes and retry > 0:247 raise RetryException()--> 248 raise_api_error(resp, http_error)249 if resp.text != '':250 return resp.json()
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:81, in raise_api_error(resp, http_error)79 error = resp.json()80 except:---> 81 raise http_error from None82 if 'message' in error:83 raise APIError(error, http_error) from None
File C:Program FilesLibsite-packagesalpaca_trade_apirest.py:243, in REST._one_request(self, method, url, opts, retry)241 resp = self._session.request(method, url, **opts)242 try:--> 243 resp.raise_for_status()244 except HTTPError as http_error:245 # retry if we hit Rate Limit246 if resp.status_code in retry_codes and retry > 0:
File C:Program FilesLibsite-packagesrequestsmodels.py:1024, in Response.raise_for_status(self)1019 http_error_msg = (1020 f"{self.status_code} Server Error: {reason} for url: {self.url}"1021 )1023 if http_error_msg:-> 1024 raise HTTPError(http_error_msg, response=self)
HTTPError: 403 Client Error: Forbidden for url: https://data.alpaca.markets/v2/stocks/GOOGL/bars?timeframe=1Day&adjustment=raw&start=2023-01-01&end=2024-01-01`
I kinda know the error means that endpoint was not found but not exactly sure. also i have no clue why im getting HTTPError: 403 Client Error and i dont know how to fix it
i run the cell expecting it to work and start collecting data. What happened was basically i got HTTPError: 403 Client Error
New contributor
nass hole is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.