A Python library to get historical forex rates from various providers.
Project description
Just Yet Another library for forex conversions
A Python library for fetching historical foreign exchange (forex) rates from various popular providers. This library aims to simplify currency conversion for a given date by abstracting away the complexities of different API integrations.
Features
- Unified Interface: Get conversion rates using a single, consistent API.
- Multiple Provider Support: Designed to support multiple forex API providers (currently includes Fixer.io, ExchangeRateHost, OpenExchangeRates).
- Historical Data: Fetch rates for specific past dates.
- Single and Multiple Currency Conversions: Convert to one or multiple currencies in a single operation.
- Secure API Key Handling: Utilizes environment variables for API key management.
Installation
You can install jyapyforex using pip:
pip install jyapyforex
API Keys
This library requires API keys from the forex rate providers you wish to use. For security, it's highly recommended to store your API keys as environment variables.
Example for Fixer.io:
-
Sign up for an API key at Fixer.io.
-
Set your API key as an environment variable:
-
Linux/macOS:
export FIXER_IO_API_KEY="your_fixer_io_api_key_here"
(Add this line to your
~/.bashrc,~/.zshrc, or equivalent for persistence) -
Windows (Command Prompt):
set FIXER_IO_API_KEY="your_fixer_io_api_key_here"
(For persistence, you'll need to set it via System Properties -> Environment Variables)
-
Windows (PowerShell):
$env:FIXER_IO_API_KEY="your_fixer_io_api_key_here"
(For persistence, you'll need to set it in your PowerShell profile)
-
Alternatively, you can pass the API keys directly to the ForexConverter constructor as a dictionary.
Following are the expected environment variables for supported providers:
| Provider | Key |
|---|---|
| Fixer.io | FIXER_IO_API_KEY |
| Open Exchange Rates | OPEN_EXCHANGE_RATES_API_KEY |
| Exchange Rate Host | EXCHANGE_RATE_HOST_API_KEY |
Usage
Here's how to use the ForexConverter to get historical exchange rates:
from jyapyforex import ForexConverter
# Initialize the converter. It will automatically look for API keys
# in environment variables or you can pass them explicitly.
try:
converter = ForexConverter()
# Example 1: Get the conversion rate from USD to EUR on a specific date
date = "2023-01-15"
from_currency = "USD"
to_currency = "EUR"
rate = converter.get_conversion_rate(from_currency, to_currency, date)
print(f"1 {from_currency} = {rate:.4f} {to_currency} on {date}")
# Example 2: Convert an amount
amount = 100.0
converted_amount = converter.convert_amount(amount, from_currency, to_currency, date)
print(f"{amount} {from_currency} = {converted_amount:.2f} {to_currency} on {date}")
# Example 3: Convert an amount to multiple currencies at once
to_currencies = ["EUR", "GBP", "JPY", "CAD"]
multi_conversions = converter.convert_amount_to_multiple_currencies(
amount=100.0,
from_currency="USD",
to_currencies=to_currencies,
date="2023-01-15"
)
print(f"100 USD on 2023-01-15 converts to:")
for currency, converted_amount in multi_conversions.items():
print(f" {converted_amount:.2f} {currency}")
# Example 4: If you want to pass API keys directly (less secure for production)
# api_keys = {
# "FIXER_IO_API_KEY": "your_api_key_here_if_not_using_env_vars"
# }
# converter_with_keys = ForexConverter(api_keys=api_keys)
# rate_direct = converter_with_keys.get_conversion_rate("GBP", "JPY", "2024-05-20")
# print(f"1 GBP = {rate_direct:.4f} JPY on 2024-05-20 (using direct keys)")
except ValueError as e:
print(f"Configuration Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
Command-Line Interface (CLI)
After installation, you can use the jyapyforex command directly from your terminal:
- Get a conversion rate:
jyapyforex rate USD EUR 2023-01-15
- Convert an amount:
jyapyforex convert 100 USD EUR 2023-01-15
- Get help:
jyapyforex --help jyapyforex rate --help
- Enable debug logging:
jyapyforex --debug rate USD EUR 2023-01-15
Testing
The library includes comprehensive unit tests covering all functionality. To run the tests:
# Install pytest if not already installed
pip install pytest
# Run all tests
pytest test/test_converters.py -v
# Run specific test class
pytest test/test_converters.py::TestConvertAmountToMultipleCurrencies -v
The test suite includes:
- Initialization tests: Validation of API key loading from environment and configuration
- Conversion rate tests: Fetching rates for single currency pairs
- Single currency conversion tests: Converting amounts between two currencies
- Multiple currency conversion tests: Converting amounts to multiple target currencies at once
- Error handling tests: Proper exception handling for invalid inputs and API failures
- Edge case tests: Zero amounts, float precision, and partial failures
API Methods
get_conversion_rate(from_currency, to_currency, date) -> float
Gets the exchange rate between two currencies for a specific date.
Parameters:
from_currency(str): Three-letter currency code (e.g., "USD")to_currency(str): Three-letter currency code (e.g., "EUR")date(str): Date in "YYYY-MM-DD" format
Returns: Float representing the exchange rate
convert_amount(amount, from_currency, to_currency, date) -> float
Converts a single amount from one currency to another for a specific date.
Parameters:
amount(float): The amount to convertfrom_currency(str): Three-letter currency codeto_currency(str): Three-letter currency codedate(str): Date in "YYYY-MM-DD" format
Returns: Float representing the converted amount
convert_amount_to_multiple_currencies(amount, from_currency, to_currencies, date) -> Dict[str, float]
Converts a single amount from one currency to multiple target currencies for a specific date.
Parameters:
amount(float): The amount to convertfrom_currency(str): Three-letter currency codeto_currencies(List[str]): List of three-letter currency codes (e.g., ["EUR", "GBP", "JPY"])date(str): Date in "YYYY-MM-DD" format
Returns: Dictionary mapping currency codes to converted amounts
Example:
result = converter.convert_amount_to_multiple_currencies(
amount=100,
from_currency="USD",
to_currencies=["EUR", "GBP", "JPY"],
date="2023-01-15"
)
# Returns: {"EUR": 92.50, "GBP": 79.30, "JPY": 12450.00}
Note: If conversion to some currencies fails, the method continues with other currencies and returns a partial result. It only raises an exception if all conversions fail.
Supported Currencies
The supported currencies depend on the integrated API providers. Generally, popular currencies like USD, EUR, GBP, JPY, CAD, AUD, CHF, etc., are widely supported. Refer to the documentation of each specific API provider (e.g., Fixer.io) for a complete list.
Adding More API Providers
To add support for a new API provider:
- Create a new Python file in
src/jyapyforex/api_clients/(e.g.,open_exchange_rates.py). - Implement a class for the new API client (e.g.,
OpenExchangeRatesClient) with aget_historical_ratemethod that matches the signature ofFixerIOClient. - Import and instantiate your new client in
src/jyapyforex/converters.pywithin the_load_api_clientsmethod, checking for its corresponding environment variable or passed API key.
Contributing
Contributions are welcome! Please feel free to open issues or submit pull requests on the GitHub repository.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jyapyforex-0.1.1.tar.gz.
File metadata
- Download URL: jyapyforex-0.1.1.tar.gz
- Upload date:
- Size: 16.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
44d5e06cb4b699b01924abc8b210cb19d01e8d098b9011a1b20947fb457e45b0
|
|
| MD5 |
8f6b5239505bacafa29f504cea9bc1b4
|
|
| BLAKE2b-256 |
a554baf468824676b45d7714d4e9944b4a47ea59dced00361643e3bc47e9082e
|
File details
Details for the file jyapyforex-0.1.1-py3-none-any.whl.
File metadata
- Download URL: jyapyforex-0.1.1-py3-none-any.whl
- Upload date:
- Size: 17.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3823c6dfcfe5f36f508ee6452b469a2f324d2bde76fd59cbddc9ae408fab6268
|
|
| MD5 |
43a1fb7adbe97b437f4ae5e3513bf7f6
|
|
| BLAKE2b-256 |
e8416cca89d27c394888f4a594f3457b558c49dbd7e728b4e4513d8e83df9c74
|