EXCHANGE_RATE
Overview
Retrieves the exchange rate from a base currency to a target currency using a public exchange rate API. Supports all 161 commonly circulating world currencies, as listed in the ExchangeRate-API Supported Currencies documentation , e.g. USD, EUR, GBP, JPY, SGD, HKD, MYR, CNY, AUD, CAD, INR, and many more. See API Documentation for details. This example function is provided as-is without any representation of accuracy.
Usage
To use the function in Excel:
=EXCHANGE_RATE(base_currency, target_currency)
base_currency
(string, required): The base currency code (e.g., “USD”).target_currency
(string, required): The target currency code (e.g., “SGD”).
The function returns the exchange rate from base to target as a float, or an error message as a string if the input or API call fails.
Examples
Example 1: USD to SGD
=EXCHANGE_RATE("USD", "SGD")
Expected output: 1.345 (actual value will vary)
Example 2: EUR to USD
=EXCHANGE_RATE("EUR", "USD")
Expected output: 1.085 (actual value will vary)
Python Code
import requests
def exchange_rate(base_currency, target_currency):
"""
Retrieves the exchange rate from a base currency to a target currency using a public API.
Args:
base_currency: The base currency code (e.g., "USD").
target_currency: The target currency code (e.g., "SGD").
Returns:
The exchange rate as a float, or an error message as a string if the input or API call fails.
This example function is provided as-is without any representation of accuracy.
"""
if not (isinstance(base_currency, str) and isinstance(target_currency, str)):
return "Error: Both base_currency and target_currency must be strings."
url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if target_currency in data.get('rates', {}):
return data['rates'][target_currency]
else:
return f"Error: Target currency '{target_currency}' not found in API response. See https://www.exchangerate-api.com/docs/supported-currencies."
else:
return f"Error: HTTP {response.status_code} when fetching exchange rates."
except Exception as e:
return f"Error: {str(e)}"
Live Notebook
Edit this function in a live notebook .