To write a Python script that uses the Open Exchange Rates API to convert currency values from Euro (EUR) to British Pound (GBP) based on historical rates corresponding to specific dates, you’ll first need to sign up for an API key from Open Exchange Rates. Once you have the API key, you can use the following Python script:
This script assumes you have two lists:
amounts_eur: A list of amounts in Euros that you want to convert.
transaction_dates: A list of dates corresponding to each transaction. Each date should be formatted as "YYYY-MM-DD".
Here’s a Python script that will perform these conversions:
# API Key from Open Exchange Rates
api_key = 'YOUR_API_KEY_HERE'
# Lists of amounts in EUR and their corresponding transaction dates
amounts_eur = [100, 200, 150] # Example amounts
transaction_dates = ['2023-01-01', '2023-01-02', '2023-01-03'] # Example dates
def convert_eur_to_gbp(amounts, dates, api_key):
# URL for historical data from Open Exchange Rates
base_url = 'https://openexchangerates.org/api/historical/{}.json'
for amount, date in zip(amounts, dates):
# Construct URL for the specific date
url = base_url.format(date)
# Parameters for the API request
response = requests.get(url, params=params)
if response.status_code == 200:
# Extract the exchange rate from EUR to GBP
exchange_rate = data['rates']['GBP']
converted_amount = amount * exchange_rate
results.append(converted_amount)
results.append(None) # Handle cases where API request fails
# Convert amounts and print results
converted_amounts_gbp = convert_eur_to_gbp(amounts_eur, transaction_dates, api_key)
print(converted_amounts_gbp)
- Replace
'YOUR_API_KEY_HERE' with your actual API key.
- The script checks the response status to handle possible errors during the API request.
- It uses the
'symbols' parameter to request only EUR and GBP rates, and sets the 'base' currency to EUR. Note that the base currency option might be restricted in free API plans, so you may need to adjust the script based on the capabilities of your plan.
If you’re working with a free plan that doesn’t support changing the base currency, you might need to adjust the script to work with the rates as provided (usually with USD as the base) and calculate the conversion rate from EUR to GBP through an intermediate conversion via USD.