Polygon.io API 使用示例:获取股票历史数据和实时报价
以下是用 Python 代码示例,展示如何通过 Polygon.io API 获取股票历史数据和实时报价:
import requests
# 设置 API 密钥和基本 URL
api_key = 'YOUR_API_KEY'
base_url = 'https://api.polygon.io'
# 获取股票历史数据
def get_stock_history(symbol, limit=10):
endpoint = f'/v2/aggs/ticker/{symbol}/range/1/day/latest?apiKey={api_key}&limit={limit}'
url = base_url + endpoint
response = requests.get(url)
if response.status_code == 200:
data = response.json()['results']
for item in data:
print(item['t'], item['o'], item['h'], item['l'], item['c'])
else:
print('Failed to fetch stock history.')
# 获取股票实时报价
def get_stock_quote(symbol):
endpoint = f'/v1/last/stocks/{symbol}?apiKey={api_key}'
url = base_url + endpoint
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data['last']['price'])
else:
print('Failed to fetch stock quote.')
# 示例用法
get_stock_history('AAPL', limit=5)
get_stock_quote('AAPL')
请确保将 YOUR_API_KEY 替换为您在 polygon.io 网站上获得的 API 密钥。
原文地址: https://www.cveoy.top/t/topic/qryq 著作权归作者所有。请勿转载和采集!