polygon-io / client-python Goto Github PK
View Code? Open in Web Editor NEWThe official Python client library for the Polygon REST and WebSocket API.
Home Page: https://polygon-api-client.readthedocs.io/
License: MIT License
The official Python client library for the Polygon REST and WebSocket API.
Home Page: https://polygon-api-client.readthedocs.io/
License: MIT License
Hi - trying to run your example code to get stock aggregated data (Query parameters for REST calls) and get AttributeError: 'StocksEquitiesAggregatesApiResponse' object has no attribute 'results.
I can't find any documentation re methods and attributes in the class. What Im missing??? Can you help?
Thanks - Mosi
I noticed that the package on pip specifies all requirements with exact versions.
This is quite annoying since it greatly increases probability of conflicts (which I now encountered).
Could you please relax the requirements? Ideally only specify the minimum version.
It doesn't appear that this value is configurable:
Am I missing something? Is there an option for using something other than DEFAULT_HOST
? I would like to use the delayed
vs. the socket
websocket endpoint as I am still in earlier evaluation stages with this product.
Running repeated calls to the Polygon Aggregates endpoint results in failure. The below chart shows failures as a function of the time waited between repeated attempts:
The below script can be used to reproduce the errors:
import json
import matplotlib.pyplot as plt
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
import time
from urllib3.util.retry import Retry
API_KEY = "*****" #your API key here
URL = f"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/minute/2020-10-14/2020-10-14?unadjusted=true&sort=asc&limit=120&apiKey={API_KEY}"
failures = {}
for pause in range(0, 30, 5):
failures[pause] = []
print(f'pause : {pause}')
for trial in range(15):
i = 0
print(f'trial : {trial}')
while True:
i += 1
print(f'i : {i}')
if i > 200:
break
try:
session = requests.Session()
retries = Retry(total=5, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retries))
r = session.get(URL)
data = r.json()
raw_df = pd.DataFrame(data["results"])
continue
except:
failures[pause].append(i)
break
with open("polygon_test_results.json", "w") as f:
json.dump(failures, f)
plt.boxplot(failures.values(), labels=failures.keys())
plt.xlabel("interval between attempts (s)")
plt.ylabel("attempts before failure")
plt.title("Polygon Endpoint Failure Analysis")
print('done')
The resulting error is:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.polygon.io', port=443): Max retries exceeded with url: /v2/aggs/ticker/AAPL/range/1/minute/2021-05-14/2021-05-17?unadjusted=true&sort=asc&limit=50000&apiKey=YTz2C7qk8BQzV1d6Og5zDOZjQ_mS8nxG (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x12c4bd450>: Failed to establish a new connection: [Errno 60] Operation timed out'))
Notably, this (repeated) error occurs when calling the url suggested in the Polygon docs to pull historical minute bar data.
The following information would help shed light on these errors:
Hi, I tried importing and it gave following error.
>>> from polygon import WebSocketClient, STOCKS_CLUSTER
Traceback (most recent call last):
File "", line 1, in
File "/Users/kshitizsharma/miniconda3/lib/python3.6/site-packages/polygon/init.py", line 1, in
from .websocket import WebSocketClient, STOCKS_CLUSTER, FOREX_CLUSTER, CRYPTO_CLUSTER
File "/Users/kshitizsharma/miniconda3/lib/python3.6/site-packages/polygon/websocket/init.py", line 1, in
from .websocket_client import WebSocketClient, STOCKS_CLUSTER, FOREX_CLUSTER, CRYPTO_CLUSTER
File "/Users/kshitizsharma/miniconda3/lib/python3.6/site-packages/polygon/websocket/websocket_client.py", line 12, in
class WebSocketClient:
File "/Users/kshitizsharma/miniconda3/lib/python3.6/site-packages/polygon/websocket/websocket_client.py", line 21, in WebSocketClient
on_error: Optional[Callable[[websocket.WebSocketApp, str], None]] = None):
AttributeError: module 'websocket' has no attribute 'WebSocketApp'_
_
Currently I'm using the websocket
library for connecting to Polygon.io and it is working.
What are the advantages to switching to this library, which I should have already known about -_-
with RESTClient(auth_key=os.environ['POLYGON_IO_APIKEY']) as client:
from_, to = self._asset.split('/')
last_ts = self._startDatetime.timestamp()
start_day_str = datetime_day_begin(self._startDatetime).strftime('%Y-%m-%d')
end_timestamp = self._endDatetime if self._endDatetime else datetime.now()
end_timestamp = end_timestamp.timestamp()
print(datetime.fromtimestamp(last_ts))
print(datetime.fromtimestamp(end_timestamp))
while last_ts < end_timestamp:
resp = client.forex_currencies_historic_forex_ticks(
from_, to, start_day_str,
offset=last_ts,
limit1=self._chunkSize)
self._chunkComplete(self._asset, resp.ticks)
if resp.ticks:
last_ts = int(resp.ticks[-1]['t'])
end_timestamp = datetime.now().timestamp()
else:
break
debug_me = True
This returns a whole slew of results, but I specified a timestamp offset of practically right this instant. I printed out the datetimes of the timestamp I'm using and it is indeed right now.
Do you have any idea how to find what the proper parameter names are to pass to the historical forex tick function?
Documentation of the python api specifically would be really useful.
I'm stuck with e.g. reference_stock_financials()
, I'd like to set the period param, but the query params are just defined as **query_params
, so I have no clue what how to specify them.
Tried to install the python client library from conda, doesn't exist. Is this expected
I was wondering if it's possible to start the pagination for /v2/ticks/stocks/nbbo/{ticker}/{date}
from an arbitrary timestamp. From playing around with the API it seems like the timestamp
parameter needs to correspond to an actual value in the dataset, otherwise the returned quotes will start at the beginning of the day. I'd like to be able to submit any timestamp in the middle of the day and get the quotes directly after this timestamp.
client-python/polygon/rest/client.py
Line 99 in 493d26f
I really can't think of a reason this function is named historic_n___bbo_quotes_v2
and not historic_nbbo_quotes_v2
.
I already opened an issue with support in the past about inconsistency in naming in the API (you use camelCase in some places and snake_case in other places and name the same field different things in different places) - so I am guessing this is probably just a mistake. Can we rename it?
Currently the Simple WebSocket Demo located in the README does not match the example file in the repo.
When I run the following python code with a debugger attached -
polygon_api = polygon.RESTClient()
response = polygon_api.stocks_equities_aggregates('AAPL', 30, 'minute', '2020-06-30', '2020-06-30')
I get a post-run warning from my debugger -
ResourceWarning: unclosed <ssl.SSLSocket type=SocketKind.SOCK_STREAM, raddr=('38.133.177.84', 443)>
But if I run -
polygon_api = polygon.RESTClient()
response = polygon_api.stocks_equities_aggregates('AAPL', 30, 'minute', '2020-06-30', '2020-06-30')
polygon_api._session.close()
The polygon client cleans up and my debugger is happy.
Looking into why this is, Session
will only call its own close()
from its __exit__
method, which is only called if the class is being used as a context manager (e.g. using with Session() as s:
statement, as suggested by their docs) - and RESTClient is not using it in this manner, so close()
is just never being called and resources are being left open.
Hi,
Great package! I'm using the prepend 'AM.' to get 1-minute bars and then internally aggregate them to 5-minutes bar. Just wondering if it's possible to subscribe for 5-minute bars from the client side?
Maybe something like
myclient.subscribe('AM.AAPL', multiplier=5)
Thanks
The example in the readme errors out:
AttributeError: 'StocksEquitiesAggregatesApiResponse' object has no attribute 'results'
Any ideas?
I used the WebSocket example provided in the README. I only added my API key, changed STOCK_CLUSTER to FOREX_CLUSTER, and changed the tickers.
While debugging, I saw that in the function subscribe()
, self._authenticated.wait()
was never stopping.
Note that it is working as expected on Windows, using python 3.7
I am trying to run a script that uses Polygon. I have the module installed:
(base) [name]-MacBook-Pro:client-python-master [name]$ pip3 install /Users/[name]/Downloads/polygon_api_client-0.1.2-py3-none-any.whl
Requirement already satisfied: polygon-api-client==0.1.2 from file:///Users/[name]/Downloads/polygon_api_client-0.1.2-py3-none-any.whl in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (0.1.2)
Requirement already satisfied: websockets==8.0.2 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from polygon-api-client==0.1.2) (8.0.2)
Requirement already satisfied: websocket-client==0.56.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from polygon-api-client==0.1.2) (0.56.0)
Requirement already satisfied: six in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from websocket-client==0.56.0->polygon-api-client==0.1.2) (1.14.0)
(base) [name]-MacBook-Pro:client-python-master [name]$
But when I try to run the script (MacBook Pro running 10.15., running Python3.8.2) I get the following error:
from polygon import RESTClient
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'polygon'
Not sure what to do next. I have uninstalled and installed using Pip3 install polygon-api-client and using the .whl installer (as shown above). I have also gone through the dependancies list and made sure that each of them are installed.
Thank you for any help you can provide.
Edit: Updated with version of Python
.reference_tickers() method doesn't populate its self.symbol attribute
JSON Example of self.resp.reference_tickers(page=1,search="microsoft"):
{'page': 1, 'perPage': 50, 'count': 2, 'status': 'OK', 'tickers': [{'ticker': 'MSFT', ..., 'url': 'https://api.polygon.io/v2/tickers/MSF'}]}
Returns a ReferenceTickersApiResponse
I found ReferenceTickersApiResponse class has its only member "symbol" for parsing the json result in List of Symbol class. Since returned JSON is in dictionary, not a list, it parses the keys from the dictionary to be its attribute and not filling in the "symbol" attribute (I believe the "symbol" attribute was meant to parse the "ticker" key from the json dictionary).
Then, If you try to access its only attribute "symbol", you get an attribute error.
When attempting to subscribe to additional symbols the subscriptions appears to fail without errors and original subscription no longer outputs messages from the websocket client session.
import time
import config
from polygon import WebSocketClient, CRYPTO_CLUSTER
def my_custom_process_message(message):
print(f"RAW: {message}")
def my_custom_error_handler(ws, error):
print(f"ERROR: {error}")
def my_custom_close_handler(ws):
print("Connection Closed")
def main():
key = 'your api key'
my_client = WebSocketClient(
cluster=CRYPTO_CLUSTER,
auth_key=key,
process_message=my_custom_process_message,
on_close=my_custom_close_handler,
on_error=my_custom_error_handler)
my_client.run_async()
print(f"Subbing: XA.BTC-USD")
my_client.subscribe("XA.BTC-USD")
time.sleep(60)
print(f"Subbing: XA.ETH-USD, XA.LTC-USD")
my_client.subscribe("XA.ETH-USD,XA.LTC-USD")
time.sleep(120)
my_client.close_connection()
if __name__ == "__main__":
main()
After the second subscription I should be receiving three messages for XA.BTC-USD, XA.ETH-USD, and XA.LTC-USD. Instead I get a timeout 20 seconds after the websocket should have returned the messages. I do receive an error stating the connection is already closed.
Output from the run:
Subbing: XA.BTC-USD
RAW: [{"ev":"status","status":"connected","message":"Connected Successfully"}]
RAW: [{"ev":"status","status":"auth_success","message":"authenticated"}]
RAW: [{"ev":"status","status":"success","message":"subscribed to: XA.BTC-USD"}]
RAW: [{"ev":"XA","pair":"BTC-USD","v":15.13028135,"vw":38937.0436,"z":0,"o":38907.83,"c":38930.31,"h":38970.4,"l":38862.75,"s":1612742760000,"e":1612742820000}]
Subbing: XA.ETH-USD, XA.LTC-USD
ERROR: Connection is already closed.
Connection Closed
Any help greatly appreciated!
from polygon import RESTClient
def main():
key = "your api key"
# RESTClient can be used as a context manager to facilitate closing the underlying http session
# https://requests.readthedocs.io/en/master/user/advanced/#session-objects
with RESTClient(key) as client:
resp = client.stocks_equities_daily_open_close("AAPL", "2018-03-02")
print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}")
if name == 'main':
main()
KeyError Traceback (most recent call last)
in
13
14 if name == 'main':
---> 15 main()
in main()
8 # https://requests.readthedocs.io/en/master/user/advanced/#session-objects
9 with RESTClient(POLYGON_API_KEY) as client:
---> 10 resp = client.stocks_equities_daily_open_close("AAPL", "2018-03-02")
11 print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}")
12
~/anaconda3/envs/test/lib/python3.8/site-packages/polygon/rest/client.py in stocks_equities_daily_open_close(self, symbol, date, **query_params)
126 **query_params) -> models.StocksEquitiesDailyOpenCloseApiResponse:
127 endpoint = f"{self.url}/v1/open-close/{symbol}/{date}"
--> 128 return self._handle_response("StocksEquitiesDailyOpenCloseApiResponse", endpoint, query_params)
129
130 def stocks_equities_condition_mappings(self, ticktype,
~/anaconda3/envs/test/lib/python3.8/site-packages/polygon/rest/client.py in _handle_response(self, response_type, endpoint, params)
31 resp: requests.Response = self._session.get(endpoint, params=params, timeout=self.timeout)
32 if resp.status_code == 200:
---> 33 return unmarshal.unmarshal_json(response_type, resp.json())
34 else:
35 resp.raise_for_status()
~/anaconda3/envs/test/lib/python3.8/site-packages/polygon/rest/models/unmarshal.py in unmarshal_json(response_type, resp_json)
6 def unmarshal_json(response_type, resp_json) -> Type[models.AnyDefinition]:
7 obj = models.name_to_classresponse_type
----> 8 obj.unmarshal_json(resp_json)
9 return obj
~/anaconda3/envs/test/lib/python3.8/site-packages/polygon/rest/models/definitions.py in unmarshal_json(self, input_json)
22 return self
23 elif isinstance(input_json, dict):
---> 24 self._unmarshal_json_object(input_json)
25 return self
26 elif isinstance(input_json, float) or isinstance(input_json, int):
~/anaconda3/envs/test/lib/python3.8/site-packages/polygon/rest/models/definitions.py in _unmarshal_json_object(self, input_json)
40 if key in self._swagger_name_to_python:
41 attribute_name = self._swagger_name_to_python[key]
---> 42 if not self._attribute_is_primitive[attribute_name]:
43 if attribute_name in self._attributes_to_types:
44 attribute_type = self._attributes_to_types[attribute_name]
KeyError: 'after_hours'
Anyone else receiving an error when trying to run the simple REST API test? This was the code I used, with my API inputted into the key definition:
from polygon import RESTClient def main(): key = "My Key" client = RESTClient(key) resp = client.stocks_equities_daily_open_close("AAPL", "2018-3-2") print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}") if __name__ == '__main__': main()
Error message received:
{"status":"ERROR","request_id":"XXX","error":"today's date not supported yet"}
let's say I make two calls, with the same timeframes, multipliers, dates, but with DIFFERENT tickers. I almost always get a different amount of bars returned. Whats going on here?? I have a feeling that no bar is returned when there is no volume traded during a one minute period.. and this screws up the aggregate? Are you working on this? Thanks.
EG.
https://api.polygon.io/v2/aggs/ticker/AMD/range/10/minute/2019-01-01/2019-01-10?limit=50000
https://api.polygon.io/v2/aggs/ticker/NVDA/range/10/minute/2019-01-01/2019-01-10?limit=50000
Hello,
I noticed that the web-socket client definition typing is:
def init(self, cluster: str, auth_key: str, process_message: Optional[Callable[[str], None]] = None,
on_close: Optional[Callable[[websocket.WebSocketApp], None]] = None,
on_error: Optional[Callable[[websocket.WebSocketApp, str], None]] = None):
However, the proper function skeleton for on_close()
is getting two parameters ( see web-socket client code)
When you call stock_equities_condition_mappings, the returned resp object is improperly unmarshalled. The call actually returns correct json object but because the returned keys are numbers, which causes the line 49 in definitions.py (function _unmarshal_json_object) to set the attribute_name to empty string. The returned object contains only empty string as key and last value which is "Errored".
The following code neither gets past the with
line nor throws any error. How can I debug it? My api key passing is correct because I used os.environ when streaming FX data and that works (with a WebSocket; haven't tried REST api).
with RESTClient(auth_key=os.environ['POLYGON_IO_APIKEY']) as client:
from_ = "AUD"
to = "JPY"
resp = client.forex_currencies_historic_forex_ticks(from_, to, ts_to_datetime(1602633600000))
for result in resp.results:
dt = ts_to_datetime(result["t"])
print(f"{dt}\n\tO: {result['o']}\n\tH: {result['h']}\n\tL: {result['l']}\n\tC: {result['c']} ")
So it doesn't even get to the other lines is what I'm saying. What can I do to fix it?
I keep getting a packages not found error. Has anyone successfully done this before?
One cannot use the client class without having websocket
and websocket-client
installed so why aren't these packages dependencies for the package? It would make life easier for everyone. ie #12
Reproduce this by running the websocket example but change the sleep time to something longer like 60 seconds. After running it for a couple seconds, try to kill the program with Ctrl-C
.
For me the data stream stops, but the Python process continues to run and won't exit unless I explicitly kill it.
Culprit here could be this.
I am trying to extract Tick data in python and save the file, is there an example please?
I tried the Demo for Rest API and changed the daily into NBBO yet i am getting an error.
Does the following user-facing function intentionally include three consecutive underscores? Just a quick note that this may be in error. Thanks for the great product!
client-python/polygon/rest/client.py
Line 89 in 02c6194
Hi guys !
I have encountered an error when I tried to connect to any websocket endpoint through this library.
self.ws_client = WebSocketClient(STOCKS_CLUSTER, token, self.__streaming_callback)
self.ws_client.run_async()
self.ws_client.subscribe("A.AAPL")
time.sleep(2)
self.ws_client.close_connection()
Right after the call to 'subscribe' method the connection was closed without showing any error.
An SSL certificate error ?
Tell me if it's a bad use on my side or if my fix is right, I managed the issue by replacing line 47 in your websocket_client.py file with this :
self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
Don't forget to import ssl in the file.
Cheers !
`with RESTClient(key) as client:
from_ = "2019-01-01"
to = "2019-02-01"
resp = client.stocks_equities_aggregates("AAPL", 1, "minute", from_, to, unadjusted=False)
print(f"Minute aggregates for {resp.ticker} between {from_} and {to}.")
count = 0
for result in resp.results:
dt = ts_to_datetime(result["t"])
#print(f"{dt}\n\tO: {result['o']}\n\tH: {result['h']}\n\tL: {result['l']}\n\tC: {result['c']} ")
count = count + 1
print(count)
`
Minute aggregates for AAPL between 2019-01-01 and 2019-02-01.
5000
last row is ''2019-01-10 11:55'
is there something I am missing ?
asyncio primitives are becoming more prevalent with Python 3, the await
keyword for example has an infectious nature.
The current Python swagger API doesn't support async, it would be good to support async in addition to Python 2.x compatible code.
aiohttp offers an interface similar to requests
.
What are your thoughts? If the API code is generated, can you suggest somewhere that asyncio could be implemented upstream to benefit your project?
The results are limited to 1000. Rest api provides url for next page, how do you use that with python ?
This should probably return an iterator instead of response.
Using this client, is it possible to save streaming data?
i copy and pasted the code adding my key. However it returned "requests.exceptions.HTTPError: 400 Client Error: Bad Request for url" When i clicked the URL. The JSON object said "error :"today's date not supported yet" ".
Im wondering, when can we get a new release with the new endpoints incorporated?
Regards,
Marcell
Can you see any problems with my downloader thread? It's now not receiving any quotes and not throwing any errors. It did throw one random connection error one time though.
import json, os
from PyQt5.QtCore import QThread, pyqtSignal
from fx_stream import ForexStream
from datetime import datetime
from polygon import RESTClient
# RESTClient can be used as a context manager to facilitate closing the underlying http session
# https://requests.readthedocs.io/en/master/user/advanced/#session-objects
from polygon_tools import datetime_day_begin, timestamp_ms
from sorted_collection import SortedCollection
DEFAULT_DOWNLOAD_CHUNK = 1000
POLYGON_IO_BASE_URL = 'https://api.polygon.io/v1/historic/forex/'
class ForexHistoryStream(ForexStream):
thread_finished = pyqtSignal()
def __init__(self, assets, start_dt, time_delay=1.0, end_dt=None, chunk_size=DEFAULT_DOWNLOAD_CHUNK):
"""
A time delay of 0 means stream as fast as possible in Python.
A nonzero time delay will mean scale time by that amount, so 0.5 would playback the ticks at half speed.
A time delay of 1.0 of course means just replay back at the rate in which the came in the past.
start_dt is the datetime object of when to start the download. Naturally, it keeps downloading
up to the present moment in time, though you can also express a stopping point with end_dt.
"""
super().__init__(assets)
assert(chunk_size <= 10000)
# Polygon.io limit, see: https://polygon.io/docs/get_v1_historic_forex__from___to___date__anchor
self._timeDelay = time_delay
self._client = None
self._startDatetime = start_dt
self._endDatetime = end_dt
self._downloadThreads = {}
self._chunkSize = chunk_size
self._downloadThread = ForexDownloadThread(assets, start_dt, end_dt, chunk_size)
self._downloadThread.finished.connect(self.thread_finished.emit)
self.data_received.connect(self.data_received.emit)
def process_message(self, msg):
msg = json.loads(msg)
if msg[0]['ev'] == 'C':
self.data_received.emit(msg)
#self.message_received.emit(msg)
def error_handler(self, err):
print(err)
def close_handler(self, ws):
print("close handler")
def subscribe(self):
self._downloadThread.start()
def add_data_callback(self, cb):
self._callbacks.append(cb)
def cancel(self):
self._downloadThread.terminate()
class ForexDownloadThread(QThread):
data_received = pyqtSignal(list)
def __init__(self, assets, start_dt, end_dt, chunk_size):
super().__init__()
self._assets = assets
self._startDatetime = start_dt
self._endDatetime = end_dt
self._chunkSize = chunk_size
def run(self):
"""
https://api.polygon.io/v1/historic/forex/AUD/USD/2020-10-14?limit=100&apiKey=<API KEY>'
For some reason this method doesn't grab just the last part of the day specified but the whole day.
So it's broken and we can only specify history resolution up to the start of a day.
But that's fine with me.
Alternatively we can just drop the first few chunks of the start day and only return the rest, but
that seems wasteful of resources.
This algorithm splices together several asset strings so that it appars just like the output
of ForexStream class.
This method cannot handle the very last part of "up to now" for that, use the ForexSeamlessStream class.
"""
with RESTClient(auth_key=os.environ['POLYGON_IO_APIKEY']) as client:
last_ts = timestamp_ms(self._startDatetime)
start_day_str = datetime_day_begin(self._startDatetime).strftime('%Y-%m-%d')
end_timestamp = timestamp_ms(self._endDatetime if self._endDatetime else datetime.now())
asset_last_ts = {
asset : int(last_ts) for asset in self._assets
}
data_chunk = SortedCollection(key=lambda x: int(x['t']))
while last_ts < end_timestamp:
for k in range(len(self._assets)):
asset = self._assets[k]
from_, to = asset.split('/')
resp = client.forex_currencies_historic_forex_ticks(
from_, to, start_day_str,
offset=asset_last_ts[asset],
limit=self._chunkSize)
if not resp.ticks:
break
for tick in resp.ticks:
tick = {
'p' : asset,
'a' : tick['ap'],
'b' : tick['bp'],
't' : tick['t']
}
data_chunk.insert(tick)
if resp.ticks:
asset_last_ts[asset] = int(resp.ticks[-1]['t'])
last_ts = min(asset_last_ts.values())
self.data_received.emit(list(data_chunk))
data_chunk.clear()
self.msleep(100)
if __name__ == '__main__':
from PyQt5.QtWidgets import QApplication
import sys
from datetime import timedelta
app = QApplication([])
fs = ForexHistoryStream(('AUD/JPY',), start_dt=datetime.now() - timedelta(0.1))
fs.subscribe()
sys.exit(app.exec_())
Hello, i can't find the functions and models for some of the v2 endpoints. In particular the last quote endpoint: /v2/last/nbbo/{stocksTicker}
am I missing something or have they not been included yet?
I'm seeing values sometimes returned w/ decimal values and other times not.
for example, todaysChangePerc can be 3.01 or 3.
the lack of consistency breaks indexing in elasticsearch and requires we manually cast every value to float before indexing.
it would be best if you cast the 3 to 3.00 on your end.
stocks_equities_last_trade_for_a_symbol uses an outdated endpoint that simply returns an error if you try to use it.
Endpoint it uses:
https://api.polygon.io/v1/last/stocks/{symbol}
Updated endpoint:
https://api.polygon.io/v2/last/trade/{symbol}
The sample would not run throwing an error on the first line with:
from polygon import RESTClient
which caused quite a lot of searching until I figured out that even with installing the client that that reference is 2 folders down the script's tree and in its own init file. Aparently VSS is stricter about references.
The fix to get the sample to work is to change that first line to:
from polygon.rest.client import RESTClient
Just hope that this helps someone else having difficulty getting to first base =;?)
Hi, is the swagger spec file for the api available publicly? The README says the clients is generated from "this swagger" but that doesn't seem to be linked anywhere. I could not find a swagger file anywhere in this repo.
I am unable to launch the websocket example file. I have installed the polygon-api-client API however I am still getting the below error. Can someone please help me figure out what I am missing or doing wrong? Thank you!
`
Message=cannot import name 'WebSocketClient' from partially initialized module 'polygon' (most likely due to a circular import) (e:\Dropbox\Documents\Visual Studio 2019\repos\polygon-client-python\websocket_example\polygon.py)
Source=E:\Dropbox\Documents\Visual Studio 2019\repos\polygon-client-python\websocket_example\polygon.py
StackTrace:
File "E:\Dropbox\Documents\Visual Studio 2019\repos\polygon-client-python\websocket_example\polygon.py", line 5, in (Current frame)
from polygon import WebSocketClient, STOCKS_CLUSTER
File "E:\Dropbox\Documents\Visual Studio 2019\repos\polygon-client-python\websocket_example\polygon.py", line 5, in
from polygon import WebSocketClient, STOCKS_CLUSTER
`
Im trying to run the sample python code for websocket but Im getting module not found.
I have installed both websocket and polygon packages using pip but no luck. Running on python 3.6
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from polygon import WebSocketClient
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/polygon.py", line 4, in <module>
from polygon import WebSocketClient, STOCKS_CLUSTER
ImportError: cannot import name 'WebSocketClient'
>>>
pip install polygon-api-client
Requirement already satisfied: polygon-api-client in /usr/local/lib/python3.6/dist-packages
pip install websocket-client
Requirement already satisfied: websocket-client in /usr/local/lib/python3.6/dist-packages
hello, everyone. newbie here.
i basically run the simple websocket demo and it gives me the error ModuleNotFoundError: No module named 'polygon'.
This I believe is line 4 in the code :
from polygon import WebSocketClient, STOCKS_CLUSTER
I have installed the polygon-api-client (pip install polygon-api-client), so I'm not sure what am I missing.
Thanks in advance.
For production keys, websocket url is polyfeed.polygon.io not socket.polygon.io.
So host should be parameterized.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.