def _fetch_symbol_details( self, session: requests.Session, ticker: Ticker ) -> Optional[Dict]: url = ( "https://api.polygon.io/" + "v1" + f"/meta/symbols/{ticker.ticker}/company" ) try: with session.get( url, params={ "apiKey": get_polygon_credentials(config.prod_api_key_id) }, ) as response: if response.status_code == 200: try: r = response.json() if r["active"]: return r except JSONDecodeError: tlog(f"JSONDecodeError for {ticker.ticker}") raise Exception(response.text) except requests.exceptions.ConnectionError as e: tlog( f"_fetch_symbol_details(): got HTTP exception {e} for {ticker.ticker}, going to sleep, then retry" ) time.sleep(30) return self._fetch_symbol_details(requests.Session(), ticker) return None
def __init__(self, key_id=None): self._key_id = get_polygon_credentials(key_id) self._endpoint = os.environ.get( 'POLYGON_WS_URL', 'wss://alpaca.socket.polygon.io/stocks').rstrip('/') self._handlers = {} self._handler_symbols = {} self._streams = set([]) self._ws = None self._retry = int(os.environ.get('APCA_RETRY_MAX', 3)) self._retry_wait = int(os.environ.get('APCA_RETRY_WAIT', 3)) self._retries = 0 self.loop = asyncio.get_event_loop()
def _get_count(self, session) -> int: url = "https://api.polygon.io/" + "v2" + "/reference/tickers" with session.get( url, params={ "apiKey": get_polygon_credentials(config.prod_api_key_id), "market": "STOCKS", "page": 1, "active": "true", "perpage": 1, }, ) as response: return response.json()["count"]
def __init__(self, api_key: str, staging: bool = False, raw_data: bool = False): """ :param staging: do we work with the staging server :param raw_data: should we return api response raw or wrap it with Entity objects. """ self._api_key: str = get_polygon_credentials(api_key) self._staging: bool = staging self._use_raw_data: bool = raw_data self._session = requests.Session()
def __init__(self, key_id: str = None, raw_data: bool = False): """ :param raw_data: should we return stream data raw or wrap it with Entity objects. """ self._key_id = get_polygon_credentials(key_id) self._endpoint: URL = URL( os.environ.get('POLYGON_WS_URL', 'wss://socket.polygon.io/stocks').rstrip('/')) self._handlers = {} self._handler_symbols = {} self._streams = set([]) self._ws = None self._retry = int(os.environ.get('APCA_RETRY_MAX', 3)) self._retry_wait = int(os.environ.get('APCA_RETRY_WAIT', 3)) self._retries = 0 self.loop = asyncio.get_event_loop() self._consume_task = None self._use_raw_data = raw_data
def _fetch(self, session: requests.Session, page: int) -> List[Ticker]: url = "https://api.polygon.io/" + "v2" + "/reference/tickers" try: with session.get( url, params={ "apiKey": get_polygon_credentials(config.prod_api_key_id), "market": "STOCKS", "page": page, "active": "true", "perpage": 50, }, ) as response: data = response.json()["tickers"] return [Ticker(x) for x in data] except requests.exceptions.ConnectionError as e: tlog( f"_fetch(): got HTTP exception {e}, for {page}, going to sleep, then retry" ) time.sleep(30) return self._fetch(requests.Session(), page)
def __init__(self, api_key, staging=False): self._api_key = get_polygon_credentials(api_key) self._staging = staging self._session = requests.Session()
async def calculate_trends(pool: Pool) -> bool: # load snapshot with requests.Session() as session: url = ("https://api.polygon.io/" + "v2/snapshot/locale/us/markets/stocks/tickers") with session.get( url, params={ "apiKey": get_polygon_credentials(config.prod_api_key_id) }, ) as response: if (response.status_code == 200 and (r := response.json())["status"] == "OK"): for ticker in r["tickers"]: trading_data.snapshot[ticker.ticker] = TickerSnapshot( symbol=ticker["ticker"], volume=ticker["day"]["volume"], today_change=ticker["todaysChangePerc"], ) if not trading_data.snapshot: tlog("calculate_trends(): market snapshot not available") return False # calculate sector trends sectors = await get_market_industries(pool) sector_tickers = {} for sector in sectors: sector_tickers[sector] = await get_sector_tickers( pool, sector) sector_volume = 0 adjusted_sum = 0.0 for symbol in sector_tickers[sector]: sector_volume += trading_data.snapshot[symbol].volume adjusted_sum += ( trading_data.snapshot[symbol].volume * trading_data.snapshot[symbol].today_change) trading_data.sector_trend[sector] = round( adjusted_sum / sector_volume, 2) # calculate industry industries = await get_market_industries(pool) industry_tickers = {} for industry in industries: industry_tickers[industry] = await get_industry_tickers( pool, industry) industry_volume = 0 adjusted_sum = 0.0 for symbol in industry_tickers[sector]: industry_volume += trading_data.snapshot[symbol].volume adjusted_sum += ( trading_data.snapshot[symbol].volume * trading_data.snapshot[symbol].today_change) trading_data.industry_trend[industry] = round( adjusted_sum / industry_volume, 2) return True