|
| 1 | +# This code retrieves stock market data for a specific stock using the |
| 2 | +# Polygon REST API and writes it to a CSV file. It uses the "polygon" |
| 3 | +# library to communicate with the API and the "csv" library to write |
| 4 | +# the data to a CSV file. The script retrieves data for the stock "AAPL" |
| 5 | +# for the dates "2023-01-30" to "2023-02-03" in 1 hour intervals. The |
| 6 | +# resulting data includes the open, high, low, close, volume, vwap, |
| 7 | +# timestamp, transactions, and otc values for each hour. The output is |
| 8 | +# then printed to the console. |
| 9 | +from polygon import RESTClient |
| 10 | +from polygon.rest.models import ( |
| 11 | + Agg, |
| 12 | +) |
| 13 | +import csv |
| 14 | +import datetime |
| 15 | +import io |
| 16 | + |
| 17 | +# docs |
| 18 | +# https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__range__multiplier___timespan___from___to |
| 19 | +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#polygon.RESTClient.get_aggs |
| 20 | + |
| 21 | +# client = RESTClient("XXXXXX") # hardcoded api_key is used |
| 22 | +client = RESTClient() # POLYGON_API_KEY environment variable is used |
| 23 | + |
| 24 | +aggs = client.get_aggs( |
| 25 | + "AAPL", |
| 26 | + 1, |
| 27 | + "hour", |
| 28 | + "2023-01-30", |
| 29 | + "2023-02-03", |
| 30 | +) |
| 31 | + |
| 32 | +print(aggs) |
| 33 | + |
| 34 | +# headers |
| 35 | +headers = [ |
| 36 | + "timestamp", |
| 37 | + "open", |
| 38 | + "high", |
| 39 | + "low", |
| 40 | + "close", |
| 41 | + "volume", |
| 42 | + "vwap", |
| 43 | + "transactions", |
| 44 | + "otc", |
| 45 | +] |
| 46 | + |
| 47 | +# creating the csv string |
| 48 | +csv_string = io.StringIO() |
| 49 | +writer = csv.DictWriter(csv_string, fieldnames=headers) |
| 50 | + |
| 51 | +# writing headers |
| 52 | +writer.writeheader() |
| 53 | + |
| 54 | +# writing data |
| 55 | +for agg in aggs: |
| 56 | + |
| 57 | + # verify this is an agg |
| 58 | + if isinstance(agg, Agg): |
| 59 | + |
| 60 | + # verify this is an int |
| 61 | + if isinstance(agg.timestamp, int): |
| 62 | + |
| 63 | + writer.writerow( |
| 64 | + { |
| 65 | + "timestamp": datetime.datetime.fromtimestamp(agg.timestamp / 1000), |
| 66 | + "open": agg.open, |
| 67 | + "high": agg.high, |
| 68 | + "low": agg.low, |
| 69 | + "close": agg.close, |
| 70 | + "volume": agg.volume, |
| 71 | + "vwap": agg.vwap, |
| 72 | + "transactions": agg.transactions, |
| 73 | + "otc": agg.otc, |
| 74 | + } |
| 75 | + ) |
| 76 | + |
| 77 | +# printing the csv string |
| 78 | +print(csv_string.getvalue()) |
0 commit comments