Extracting Data from Polygon.io
Getting Historical Data from Polygon.io
Accessing historical market data is essential for various financial analyses, backtesting trading strategies, and performing quantitative research. Polygon.io is a popular platform that provides comprehensive financial market data, including historical data, across multiple asset classes. In this article, we’ll guide you through the process of getting historical data from Polygon.io, from setting up your account to retrieving the data using their API.
Setting Up Your Polygon.io Account
Understanding Polygon.io Data Types
Polygon.io provides various types of market data, including:
For this article, we’ll focus on retrieving historical stock data, but the process is similar for other data types.
Retrieving Historical Data
Polygon.io offers a comprehensive API to access historical data. Below is a step-by-step guide to fetching historical stock data using Python.
Step 1: Install Required Libraries
First, ensure you have the necessary Python libraries installed. You can install them using pip:
pip install requests pandas
Step 2: Set Up Your Python Script
Next, create a Python script and import the required libraries. Use your API key to authenticate your requests.
# Replace 'YOUR_API_KEY' with your actual API key
API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://api.polygon.io'
def get_histdata_polygon(ticker, start_date, end_date, timespan, multiplier):
url = f"{BASE_URL}/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{start_date}/{end_date}?apiKey={API_KEY}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
df = pd.DataFrame(data['results'])
# Convert timestamp to datetime format
df['timestamp'] = pd.to_datetime(df['t'], unit='ms')
# Reorganize columns
columns = ['timestamp', 'o', 'h', 'l', 'c', 'v']
df = df[['timestamp', 'o', 'h', 'l', 'c', 'v']]
# Rename columns for clarity
df.columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']
# Set timestamp as index
df.set_index('timestamp', inplace=True)
return df
elif response.status_code == 403:
print("Error 403: Forbidden. Check your API key and subscription plan.")
else:
print(f"Error: {response.status_code} - {response.text}")
return pd.DataFrame()
领英推荐
# Example usage
ticker = 'AAPL'
start_date = '2024-01-05'
end_date = '2024-01-06'
timespan = 'minute' # Can be 'minute', 'hour', 'day', etc.
multiplier = 5 # For 5-minute intervals
data = get_histdata_polygon(ticker, start_date, end_date, timespan, multiplier)
Step 3: Customize and Analyze the Data
The above script fetches daily historical data for a specified stock ticker (e.g., AAPL) between the start and end dates. You can customize the script to handle different tickers, date ranges, and frequencies (e.g., minute, hour, day).
Once you have the data in a DataFrame, you can perform various analyses, such as calculating moving averages, plotting price trends, or backtesting trading strategies.
Conclusion
Fetching historical data from Polygon.io is a straightforward process once you set up your account and understand the API. By following the steps outlined in this article, you can retrieve and analyze historical market data to support your financial analyses and trading strategies. Remember to respect API rate limits and handle errors gracefully in your scripts to ensure smooth data retrieval.