From d2e7ed845a12f50cf0cafb9188e0accbc50ecf2f Mon Sep 17 00:00:00 2001 From: zack <43246297+clickingbuttons@users.noreply.github.com> Date: Mon, 2 May 2022 11:57:39 -0400 Subject: [PATCH] fix non-list return types --- polygon/rest/aggs.py | 2 +- polygon/rest/base.py | 10 +- polygon/rest/models/trades.py | 17 --- polygon/rest/trades.py | 7 +- tests/test_aggs.py | 27 ++--- tests/test_markets.py | 26 ++-- tests/test_snapshots.py | 216 +++++++++++++++++----------------- tests/test_tickers.py | 72 ++++++------ tests/test_trades.py | 56 ++++----- 9 files changed, 198 insertions(+), 235 deletions(-) diff --git a/polygon/rest/aggs.py b/polygon/rest/aggs.py index da77d97e..26ef7153 100644 --- a/polygon/rest/aggs.py +++ b/polygon/rest/aggs.py @@ -56,7 +56,7 @@ def get_grouped_daily_aggs( adjusted: Optional[bool] = None, params: Optional[Dict[str, Any]] = None, raw: bool = False, - ) -> Union[List[GroupedDailyAgg], HTTPResponse]: + ) -> Union[GroupedDailyAgg, HTTPResponse]: """ Get the daily open, high, low, and close (OHLC) for the entire market. diff --git a/polygon/rest/base.py b/polygon/rest/base.py index f719a8e9..ac970d3c 100644 --- a/polygon/rest/base.py +++ b/polygon/rest/base.py @@ -72,13 +72,11 @@ def _get( if result_key: obj = obj[result_key] - # If obj is not yet a list, need to turn it into a list - # This is for the Daily Open/Close and Last Trade endpoints - if type(obj) != list: - obj = [obj] - if deserializer: - obj = [deserializer(o) for o in obj] + if type(obj) == list: + obj = [deserializer(o) for o in obj] + else: + obj = deserializer(obj) return obj diff --git a/polygon/rest/models/trades.py b/polygon/rest/models/trades.py index e14cfa0b..0ff3195e 100644 --- a/polygon/rest/models/trades.py +++ b/polygon/rest/models/trades.py @@ -69,20 +69,3 @@ class Last: @staticmethod def from_dict(d): return Last(**d) - - -@dataclass -class LastTradeCrypto: - last: Last - ticker: str - status: str - request_id: str - - @staticmethod - def from_dict(d): - return LastTradeCrypto( - d.get("last", None), - d.get("symbol", None), - d.get("status", None), - d.get("request_id", None), - ) diff --git a/polygon/rest/trades.py b/polygon/rest/trades.py index 89dd24eb..b02e2f1e 100644 --- a/polygon/rest/trades.py +++ b/polygon/rest/trades.py @@ -1,6 +1,6 @@ from .base import BaseClient from typing import Optional, Any, Dict, Union, Iterator -from .models import Trade, LastTrade, LastTradeCrypto, Sort, Order +from .models import Trade, LastTrade, Last, Sort, Order from urllib3 import HTTPResponse from datetime import datetime, date @@ -75,7 +75,7 @@ def get_last_trade_crypto( to: str, params: Optional[Dict[str, Any]] = None, raw: bool = False, - ) -> Union[LastTrade, HTTPResponse]: + ) -> Union[Last, HTTPResponse]: """ Get the most recent trade for a ticker. @@ -89,6 +89,7 @@ def get_last_trade_crypto( return self._get( path=url, params=self._get_params(self.get_last_trade_crypto, locals()), - deserializer=LastTradeCrypto.from_dict, + result_key="last", + deserializer=Last.from_dict, raw=raw, ) diff --git a/tests/test_aggs.py b/tests/test_aggs.py index f5e0edb8..08706c53 100644 --- a/tests/test_aggs.py +++ b/tests/test_aggs.py @@ -53,20 +53,19 @@ def test_get_grouped_daily_aggs(self): def test_get_daily_open_close_agg(self): aggs = self.c.get_daily_open_close_agg("AAPL", "2005-04-01", True) - expected = [ - DailyOpenCloseAgg( - after_hours=123, - close=123, - from_="2021-04-01", - high=124.18, - low=122.49, - open=123.66, - pre_market=123.45, - status="OK", - symbol="AAPL", - volume=75089134, - ) - ] + expected = DailyOpenCloseAgg( + after_hours=123, + close=123, + from_="2021-04-01", + high=124.18, + low=122.49, + open=123.66, + pre_market=123.45, + status="OK", + symbol="AAPL", + volume=75089134, + ) + self.assertEqual(aggs, expected) def test_get_previous_close_agg(self): diff --git a/tests/test_markets.py b/tests/test_markets.py index 61fa4dba..c0654747 100644 --- a/tests/test_markets.py +++ b/tests/test_markets.py @@ -123,18 +123,16 @@ def test_get_market_holidays(self): def test_get_market_status(self): status = self.c.get_market_status() - expected = [ - MarketStatus( - after_hours=True, - currencies={"fx": "open", "crypto": "open"}, - early_hours=False, - exchanges={ - "nyse": "extended-hours", - "nasdaq": "extended-hours", - "otc": "extended-hours", - }, - market="extended-hours", - server_time="2022-04-28T16:48:08-04:00", - ) - ] + expected = MarketStatus( + after_hours=True, + currencies={"fx": "open", "crypto": "open"}, + early_hours=False, + exchanges={ + "nyse": "extended-hours", + "nasdaq": "extended-hours", + "otc": "extended-hours", + }, + market="extended-hours", + server_time="2022-04-28T16:48:08-04:00", + ) self.assertEqual(status, expected) diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index 3e9729db..ba97b1a9 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -155,123 +155,117 @@ def test_get_snapshot_direction(self): def test_get_snapshot_ticker(self): snapshots = self.c.get_snapshot_ticker("AAPL") - expected = [ - Snapshot( - day={ - "c": 160.315, - "h": 166.2, - "l": 159.8, - "o": 161.84, - "v": 68840127, - "vw": 162.7124, - }, - last_quote={ - "P": 159.99, - "S": 5, - "p": 159.98, - "s": 3, - "t": 1651251948407646487, - }, - last_trade={ - "c": None, - "i": "121351", - "p": 159.99, - "s": 200, - "t": 1651251948294080343, - "x": 12, - }, - min={ - "av": 68834255, - "c": 160.3, - "h": 160.71, - "l": 160.3, - "o": 160.71, - "v": 197226, - "vw": 160.5259, - }, - prev_day={ - "c": 163.64, - "h": 164.515, - "l": 158.93, - "o": 159.25, - "v": 130149192, - "vw": 161.8622, - }, - ticker="AAPL", - todays_change=-3.65, - todays_change_percent=None, - updated=1651251948294080343, - ) - ] + expected = Snapshot( + day={ + "c": 160.315, + "h": 166.2, + "l": 159.8, + "o": 161.84, + "v": 68840127, + "vw": 162.7124, + }, + last_quote={ + "P": 159.99, + "S": 5, + "p": 159.98, + "s": 3, + "t": 1651251948407646487, + }, + last_trade={ + "c": None, + "i": "121351", + "p": 159.99, + "s": 200, + "t": 1651251948294080343, + "x": 12, + }, + min={ + "av": 68834255, + "c": 160.3, + "h": 160.71, + "l": 160.3, + "o": 160.71, + "v": 197226, + "vw": 160.5259, + }, + prev_day={ + "c": 163.64, + "h": 164.515, + "l": 158.93, + "o": 159.25, + "v": 130149192, + "vw": 161.8622, + }, + ticker="AAPL", + todays_change=-3.65, + todays_change_percent=None, + updated=1651251948294080343, + ) self.assertEqual(snapshots, expected) def test_get_snapshot_option(self): snapshots = self.c.get_snapshot_option("AAPL", "O:AAPL230616C00150000") - expected = [ - OptionContractSnapshot( - break_even_price=179.075, - day={ - "change": -2.3999999999999986, - "change_percent": -7.643312101910824, - "close": 29, - "high": 32.25, - "last_updated": 1651204800000000000, - "low": 29, - "open": 29.99, - "previous_close": 31.4, - "volume": 8, - "vwap": 30.7738, - }, - details={ - "contract_type": "call", - "exercise_style": "american", - "expiration_date": "2023-06-16", - "shares_per_contract": 100, - "strike_price": 150, - "ticker": "O:AAPL230616C00150000", - }, - greeks={ - "delta": 0.6436614934293701, - "gamma": 0.0061735291012820675, - "theta": -0.028227189324641973, - "vega": 0.6381159723175714, - }, - implied_volatility=0.3570277203465058, - last_quote={ - "ask": 29.25, - "ask_size": 209, - "bid": 28.9, - "bid_size": 294, - "last_updated": 1651254260800059648, - "midpoint": 29.075, - "timeframe": "REAL-TIME", - }, - open_interest=8133, - underlying_asset={ - "change_to_break_even": 19.11439999999999, - "last_updated": 1651254263172073152, - "price": 159.9606, - "ticker": "AAPL", - "timeframe": "REAL-TIME", - }, - ) - ] + expected = OptionContractSnapshot( + break_even_price=179.075, + day={ + "change": -2.3999999999999986, + "change_percent": -7.643312101910824, + "close": 29, + "high": 32.25, + "last_updated": 1651204800000000000, + "low": 29, + "open": 29.99, + "previous_close": 31.4, + "volume": 8, + "vwap": 30.7738, + }, + details={ + "contract_type": "call", + "exercise_style": "american", + "expiration_date": "2023-06-16", + "shares_per_contract": 100, + "strike_price": 150, + "ticker": "O:AAPL230616C00150000", + }, + greeks={ + "delta": 0.6436614934293701, + "gamma": 0.0061735291012820675, + "theta": -0.028227189324641973, + "vega": 0.6381159723175714, + }, + implied_volatility=0.3570277203465058, + last_quote={ + "ask": 29.25, + "ask_size": 209, + "bid": 28.9, + "bid_size": 294, + "last_updated": 1651254260800059648, + "midpoint": 29.075, + "timeframe": "REAL-TIME", + }, + open_interest=8133, + underlying_asset={ + "change_to_break_even": 19.11439999999999, + "last_updated": 1651254263172073152, + "price": 159.9606, + "ticker": "AAPL", + "timeframe": "REAL-TIME", + }, + ) self.assertEqual(snapshots, expected) def test_get_snapshot_crypto_book(self): snapshots = self.c.get_snapshot_crypto_book("X:BTCUSD") - expected = [ - SnapshotTickerFullBook( - ticker="X:BTCUSD", - bids=[ - {"p": 16303.17, "x": {"1": 2}}, - {"p": 16302.94, "x": {"1": 0.02859424, "6": 0.023455}}, - ], - asks=[{"p": 11454, "x": {"2": 1}}, {"p": 11455, "x": {"2": 1}}], - bid_count=694.951789670001, - ask_count=593.1412981600005, - spread=-4849.17, - updated=1605295074162, - ) - ] + expected = SnapshotTickerFullBook( + ticker="X:BTCUSD", + bids=[ + {"p": 16303.17, "x": {"1": 2}}, + {"p": 16302.94, "x": {"1": 0.02859424, "6": 0.023455}}, + ], + asks=[{"p": 11454, "x": {"2": 1}}, {"p": 11455, "x": {"2": 1}}], + bid_count=694.951789670001, + ask_count=593.1412981600005, + spread=-4849.17, + updated=1605295074162, + ) self.assertEqual(snapshots, expected) diff --git a/tests/test_tickers.py b/tests/test_tickers.py index 18b9c733..6af121c4 100644 --- a/tests/test_tickers.py +++ b/tests/test_tickers.py @@ -88,43 +88,41 @@ def test_list_tickers(self): def test_get_ticker_details(self): details = self.c.get_ticker_details("AAPL") - expected = [ - TickerDetails( - active=True, - address={ - "address1": "ONE APPLE PARK WAY", - "city": "CUPERTINO", - "state": "CA", - "postal_code": "95014", - }, - branding={ - "logo_url": "https://api.polygon.io/v1/reference/company-branding/d3d3LmFwcGxlLmNvbQ/images/2022-02-01_logo.svg", - "icon_url": "https://api.polygon.io/v1/reference/company-branding/d3d3LmFwcGxlLmNvbQ/images/2022-02-01_icon.png", - }, - cik="0000320193", - composite_figi="BBG000B9XRY4", - currency_name="usd", - delisted_utc=None, - description="Apple designs a wide variety of consumer electronic devices, including smartphones (iPhone), tablets (iPad), PCs (Mac), smartwatches (Apple Watch), AirPods, and TV boxes (Apple TV), among others. The iPhone makes up the majority of Apples total revenue. In addition, Apple offers its customers a variety of services such as Apple Music, iCloud, Apple Care, Apple TV+, Apple Arcade, Apple Card, and Apple Pay, among others. Apples products run internally developed software and semiconductors, and the firm is well known for its integration of hardware, software and services. Apples products are distributed online as well as through company-owned stores and third-party retailers. The company generates roughly 40 of its revenue from the Americas, with the remainder earned internationally.", - ticker_root="AAPL", - homepage_url="https://www.apple.com", - list_date="1980-12-12", - locale="us", - market="stocks", - market_cap=2671492491700.0, - name="Apple Inc.", - phone_number="(408) 996-1010", - primary_exchange="XNAS", - share_class_figi="BBG001S5N8V8", - share_class_shares_outstanding=16319440000, - sic_code="3571", - sic_description="ELECTRONIC COMPUTERS", - ticker="AAPL", - total_employees=154000, - type="CS", - weighted_shares_outstanding=16319441000, - ) - ] + expected = TickerDetails( + active=True, + address={ + "address1": "ONE APPLE PARK WAY", + "city": "CUPERTINO", + "state": "CA", + "postal_code": "95014", + }, + branding={ + "logo_url": "https://api.polygon.io/v1/reference/company-branding/d3d3LmFwcGxlLmNvbQ/images/2022-02-01_logo.svg", + "icon_url": "https://api.polygon.io/v1/reference/company-branding/d3d3LmFwcGxlLmNvbQ/images/2022-02-01_icon.png", + }, + cik="0000320193", + composite_figi="BBG000B9XRY4", + currency_name="usd", + delisted_utc=None, + description="Apple designs a wide variety of consumer electronic devices, including smartphones (iPhone), tablets (iPad), PCs (Mac), smartwatches (Apple Watch), AirPods, and TV boxes (Apple TV), among others. The iPhone makes up the majority of Apples total revenue. In addition, Apple offers its customers a variety of services such as Apple Music, iCloud, Apple Care, Apple TV+, Apple Arcade, Apple Card, and Apple Pay, among others. Apples products run internally developed software and semiconductors, and the firm is well known for its integration of hardware, software and services. Apples products are distributed online as well as through company-owned stores and third-party retailers. The company generates roughly 40 of its revenue from the Americas, with the remainder earned internationally.", + ticker_root="AAPL", + homepage_url="https://www.apple.com", + list_date="1980-12-12", + locale="us", + market="stocks", + market_cap=2671492491700.0, + name="Apple Inc.", + phone_number="(408) 996-1010", + primary_exchange="XNAS", + share_class_figi="BBG001S5N8V8", + share_class_shares_outstanding=16319440000, + sic_code="3571", + sic_description="ELECTRONIC COMPUTERS", + ticker="AAPL", + total_employees=154000, + type="CS", + weighted_shares_outstanding=16319441000, + ) self.assertEqual(details, expected) def test_list_ticker_news(self): diff --git a/tests/test_trades.py b/tests/test_trades.py index 91f5ba66..7ea38e60 100644 --- a/tests/test_trades.py +++ b/tests/test_trades.py @@ -2,48 +2,40 @@ from polygon.rest.models import ( Trade, LastTrade, - LastTradeCrypto, + Last, ) class TradesTest(BaseTest): def test_get_last_trade(self): last_trade = self.c.get_last_trade("AAPL") - expected = [ - LastTrade( - ticker="AAPL", - trf_timestamp=1651179319310588400, - sequence_number=7084210, - sip_timestamp=1651179319310617300, - participant_timestamp=1651179319308000000, - conditions=[12, 37], - correction=None, - id="237688", - price=166.25, - trf_id=202, - size=2, - exchange=4, - tape=3, - ) - ] + expected = LastTrade( + ticker="AAPL", + trf_timestamp=1651179319310588400, + sequence_number=7084210, + sip_timestamp=1651179319310617300, + participant_timestamp=1651179319308000000, + conditions=[12, 37], + correction=None, + id="237688", + price=166.25, + trf_id=202, + size=2, + exchange=4, + tape=3, + ) + self.assertEqual(last_trade, expected) def test_get_last_trade_crypto(self): last_trade_crypto = self.c.get_last_trade_crypto("BTC", "USD") - expected = [ - LastTradeCrypto( - last={ - "conditions": [2], - "exchange": 2, - "price": 39976.89682331, - "size": 0.005, - "timestamp": 1651180409688, - }, - ticker="BTC-USD", - status="success", - request_id="d67c9bfe1fa0c29db9177d78b3ab713c", - ) - ] + expected = Last( + conditions=[2], + exchange=2, + price=39976.89682331, + size=0.005, + timestamp=1651180409688, + ) self.assertEqual(last_trade_crypto, expected) def test_trades(self):