How to Analyze Currency Pairs with Python and Polygon API
Introduction
In this article, we will explore how to use the Polygon API to extract financial data, specifically currency pair data, and analyze it using Python. We will implement a script that allows us to obtain forex data, format it, and calculate relevant metrics such as daily return and the relationship between transaction volume and trading volume.
Problematic of Extracting Forex Data
Extracting forex data can be challenging due to the following reasons:
- Data Volume: Forex markets generate vast amounts of data every second, making manual extraction and processing impractical.
- Data Accuracy: Ensuring the accuracy and timeliness of the data is crucial for effective analysis.
- Complexity: Forex data comes in various formats and includes multiple parameters, requiring significant effort to clean and format for analysis.
How This Script Helps Automate the Task
This script automates the extraction, formatting, and analysis of forex data, addressing the above challenges:
- Efficiency: Automates the process of data retrieval, reducing manual effort and time.
- Accuracy: Ensures accurate and timely data extraction from a reliable source.
- Consistency: Formats the data uniformly, making it easier to analyze and interpret.
- Scalability: Can be adapted to handle larger datasets and different currency pairs or financial instruments.
By using this script, analysts can focus more on interpreting the data and making informed decisions rather than spending time on data extraction and preprocessing.
Introduction to the Polygon API
Polygon is a widely used platform that offers financial data in an accessible manner. Its REST API provides data from various financial markets, including stocks, options, indices, forex, and cryptocurrencies. To start using it, we need to obtain an API Key by registering on their website.
Initial Setup
- Obtain the API Key: Register on Polygon, get your API Key, and save it. This key will be necessary to authenticate our API requests.
- Install Required Libraries: Make sure to have the
requestsandpandaslibraries installed in your Python environment.
Extracting Data
The first step is to build the API URL to extract forex data. The URL is constructed using parameters such as the currency pair, multiplier, time range, and others. Here is an example of how to build and call the API:
import requests
import pandas as pd
def get_forex_data(api_key, start_date, end_date, multiplier, timespan, from_currency, to_currency):
url = f"https://api.polygon.io/v2/aggs/ticker/C:{from_currency}{to_currency}/range/{multiplier}/{timespan}/{start_date}/{end_date}?apiKey={api_key}"
response = requests.get(url)
data = response.json()['results']
return data
api_key = 'YOUR_API_KEY'
forex_data = get_forex_data(api_key, '2023-01-01', '2023-12-31', 1, 'day', 'EUR', 'USD')Formatting and Analyzing Data
Once we have the data, we will format it into a pandas DataFrame and calculate relevant metrics.
- Format the Data: Transform the timestamp into a readable format and set it as the index of the DataFrame.
df = pd.DataFrame(forex_data)
df['timestamp'] = pd.to_datetime(df['t'], unit='ms')
df.set_index('timestamp', inplace=True)
df.drop(columns=['t'], inplace=True)2. Calculate Returns: Calculate the daily return as the percentage change in the closing price.
df['return'] = df['c'].pct_change()3. Transaction Volume: Calculate the weighted volume, a technical indicator used to reflect the price based on volume.
df['weighted_volume'] = (df['c'] * df['v']).cumsum() / df['v'].cumsum()Exporting Data
Finally, we export the data to an Excel file for easier analysis.
df.to_excel('forex_data.xlsx')Complete Example
Here is the complete code to obtain, format, analyze, and export currency pair data using the Polygon API and Python.
import requests
import pandas as pd
def get_forex_data(api_key, start_date, end_date, multiplier, timespan, from_currency, to_currency):
url = f"https://api.polygon.io/v2/aggs/ticker/C:{from_currency}{to_currency}/range/{multiplier}/{timespan}/{start_date}/{end_date}?apiKey={api_key}"
response = requests.get(url)
data = response.json()['results']
return data
api_key = 'YOUR_API_KEY'
forex_data = get_forex_data(api_key, '2023-01-01', '2023-12-31', 1, 'day', 'EUR', 'USD')
df = pd.DataFrame(forex_data)
df['timestamp'] = pd.to_datetime(df['t'], unit='ms')
df.set_index('timestamp', inplace=True)
df.drop(columns=['t'], inplace=True)
df['return'] = df['c'].pct_change()
df['weighted_volume'] = (df['c'] * df['v']).cumsum() / df['v'].cumsum()
df.to_excel('forex_data.xlsx')The output
I recommend running the command start forex_data.xlsx in the console to open quickly the file
Conclusion
In this article, we have seen how to use the Polygon API to obtain currency pair data and analyze it with Python. This process allows us to calculate important technical indicators and export the data for more detailed analysis. This methodology can be applied to different types of financial markets, offering a powerful tool for financial analysis.
Get Kevin Meneses González’s stories in your inbox
Join Medium for free to get updates from this writer.
Follow me on Linkedin
https://www.linkedin.com/in/kevin-meneses-897a28127/
and Medium
https://medium.com/@kevinmenesesgonzalez/subscribe
Subscribe to my Data Pulse Newsletter
https://www.linkedin.com/newsletters/datapulse-python-finance-7208914833608478720









