Skip to main content

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:

  1. Sign up for an API key at Fixer.io.

  2. 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 convert
  • from_currency (str): Three-letter currency code
  • to_currency (str): Three-letter currency code
  • date (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 convert
  • from_currency (str): Three-letter currency code
  • to_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:

  1. Create a new Python file in src/jyapyforex/api_clients/ (e.g., open_exchange_rates.py).
  2. Implement a class for the new API client (e.g., OpenExchangeRatesClient) with a get_historical_rate method that matches the signature of FixerIOClient.
  3. Import and instantiate your new client in src/jyapyforex/converters.py within the _load_api_clients method, 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.

Metadata

Release files for jyapyforex 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jyapyforex 0.1.1
File Size Uploaded
jyapyforex-0.1.1.tar.gz 16.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for jyapyforex 0.1.1
File Interpreter ABI Platform
jyapyforex-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 33.8 kB

Release files / jyapyforex-0.1.1.tar.gz

Download URL jyapyforex-0.1.1.tar.gz
Size 16.5 kB
Tags Source
SHA-256 checksum
How to use checksums
44d5e06cb4b699b01924abc8b210cb19d01e8d098b9011a1b20947fb457e45b0
BLAKE2b-256 checksum
How to use checksums
a554baf468824676b45d7714d4e9944b4a47ea59dced00361643e3bc47e9082e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.4

Release files / jyapyforex-0.1.1-py3-none-any.whl

Download URL jyapyforex-0.1.1-py3-none-any.whl
Size 17.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3823c6dfcfe5f36f508ee6452b469a2f324d2bde76fd59cbddc9ae408fab6268
BLAKE2b-256 checksum
How to use checksums
e8416cca89d27c394888f4a594f3457b558c49dbd7e728b4e4513d8e83df9c74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.4

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page