### Install CurrencyConverter using setup.py Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Install the library directly from the source code after cloning the repository. ```bash $ python setup.py install --user ``` -------------------------------- ### Install CurrencyConverter using pip Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Install the library using pip for easy management of Python packages. ```bash $ pip install --user currencyconverter ``` -------------------------------- ### CLI Usage Example: Basic Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Demonstrates a basic command-line conversion of 100 USD to EUR. This is the simplest use case for the tool. ```bash currency_converter 100 USD --to EUR ``` -------------------------------- ### CLI Usage Example: Conversion with Date Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Shows how to perform a currency conversion for a specific historical date. Requires specifying the target currency and date. ```bash currency_converter 100 EUR --to USD --date 2014-03-28 ``` -------------------------------- ### CLI Usage Example: Show Available Currencies Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Illustrates how to display a list of available currencies using the verbose flag. Use -v for a basic list and -vv for more details. ```bash currency_converter 100 EUR -v ``` -------------------------------- ### Example of ValueError for Unsupported Currency Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Demonstrates how a ValueError is raised when attempting to convert with an unsupported currency code. ```python from currency_converter import CurrencyConverter c = CurrencyConverter() try: c.convert(100, 'AAA') except ValueError as e: print(str(e)) # Output: "AAA is not a supported currency" ``` -------------------------------- ### CLI Usage Example: Decimal Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Shows how to use the --decimal flag for exact conversions using Python's Decimal type. This is recommended for financial calculations requiring high precision. ```bash currency_converter 100 EUR --decimal ``` -------------------------------- ### CurrencyConverter Convert Method Examples Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/CurrencyConverter.md Demonstrates various ways to use the `convert` method for currency conversion, including default currency, specific dates, and handling errors. Requires `CurrencyConverter` and `datetime` imports. ```python from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter() # Convert to default currency (EUR) result = c.convert(100, 'USD') print(result) # ~72.67 (uses latest rate) # Convert between two currencies on a specific date result = c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(result) # 129.1 # Convert from USD to EUR on a specific date result = c.convert(100, 'USD', 'EUR', date=date(2014, 3, 28)) print(result) # ~72.68 # Using datetime object (accepts both date and datetime) from datetime import datetime result = c.convert(100, 'EUR', 'USD', datetime(2013, 3, 21, 12, 30)) print(result) # 129.1 # Error: unsupported currency try: c.convert(100, 'AAA') except ValueError as e: print(e) # "AAA is not a supported currency" # Error: no rate available try: c.convert(100, 'BGN', date=date(2010, 11, 21)) except Exception as e: print(type(e).__name__) # RateNotFoundError ``` -------------------------------- ### Using Valid Fallback Methods in CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Shows how to initialize CurrencyConverter with valid fallback methods: 'linear_interpolation' for weighted averages and 'last_known' for forward-filling rates. Includes example usage for converting currency. ```python from currency_converter import CurrencyConverter from datetime import date # Method 1: Linear interpolation (weighted average) c1 = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="linear_interpolation" ) result1 = c1.convert(10, 'USD', date=date(2019, 12, 8)) # ~9.02 # Method 2: Last known rate (forward-fill) c2 = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="last_known" ) result2 = c2.convert(10, 'USD', date=date(2019, 12, 8)) # ~9.01 print(f"Linear interpolation: {result1}") print(f"Last known: {result2}") ``` -------------------------------- ### CLI Usage Example: Detailed Verbose Output Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Demonstrates obtaining detailed verbose output, including information about missing rate data. This is useful for debugging or understanding data limitations. ```bash currency_converter 100 EUR -vv ``` -------------------------------- ### Access Supported Currencies - Python Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Instantiate the CurrencyConverter and print the set of supported currencies and their count. Ensure the package is installed. ```python c = CurrencyConverter() print(c.currencies) # {'EUR', 'USD', 'GBP', 'JPY', ...} print(len(c.currencies)) # Number of currencies ``` -------------------------------- ### Comparing Float and Decimal Return Types Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Illustrates the difference in return types and precision between float and Decimal conversions. The example shows how to check the type and observe the output format for both. ```python from currency_converter import CurrencyConverter from decimal import Decimal from datetime import date c_float = CurrencyConverter(decimal=False) c_decimal = CurrencyConverter(decimal=True) # Float result f_result = c_float.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(type(f_result).__name__) # float print(f_result) # 129.1 # Decimal result d_result = c_decimal.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(type(d_result).__name__) # Decimal print(d_result) # Decimal('129.100') # Decimal has more precision print(c_decimal.convert(10, 'USD', 'EUR', date=date(2014, 3, 28))) # Decimal('7.267970055963369430917944618') ``` -------------------------------- ### Smart Caching for Currency Data Download Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/configuration.md Shows how to implement smart caching for downloading currency data. This example checks if the file for the current day exists and downloads it from the ECB URL only if it's not present, ensuring data is downloaded once per day. ```python import os.path as op from datetime import date import urllib.request filename = f"ecb_{{date.today():%Y%m%d}}.zip" if not op.isfile(filename): urllib.request.urlretrieve(ECB_URL, filename) c5 = CurrencyConverter(filename) ``` -------------------------------- ### S3CurrencyConverter Inheritance Example Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/S3CurrencyConverter.md Demonstrates using inherited methods and attributes from the parent CurrencyConverter class with an S3CurrencyConverter instance. Configuration options like `decimal` and `fallback_on_wrong_date` are also shown. ```python from currency_converter import S3CurrencyConverter import boto from datetime import date key = boto.connect_s3().get_bucket('data').get_key('rates.zip') c = S3CurrencyConverter(key, decimal=True, fallback_on_wrong_date=True) # All parent methods available print(c.currencies) # {'EUR', 'USD', 'GBP', ...} print(c.bounds['USD']) # Bounds(first_date=..., last_date=...) result = c.convert(100, 'EUR', 'USD', date=date(2014, 3, 28)) print(type(result).__name__) # Decimal ``` -------------------------------- ### Example Usage of Bounds Named Tuple Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Demonstrates how to use the `Bounds` named tuple with `CurrencyConverter`. Shows accessing currency bounds, fields by name and index, unpacking, and date comparisons. Also includes creating custom `Bounds` objects. ```python from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter() # Access bounds for a currency usd_bounds = c.bounds['USD'] print(type(usd_bounds).__name__) # bounds # Access fields by name print(usd_bounds.first_date) # 1999-01-04 print(usd_bounds.last_date) # 2025-12-31 # Unpack the tuple first, last = usd_bounds print(f"Available from {first} to {last}") # Use in date comparisons target_date = date(2010, 1, 1) if target_date >= usd_bounds.first_date and target_date <= usd_bounds.last_date: print("Rate available for this date") else: print("Date outside available range") # Access by index print(usd_bounds[0]) # 1999-01-04 print(usd_bounds[1]) # 2025-12-31 # Iterate for date_obj in usd_bounds: print(date_obj) # Create custom Bounds (if needed) from currency_converter.currency_converter import Bounds custom_bounds = Bounds(date(2010, 1, 1), date(2020, 12, 31)) print(custom_bounds) # Bounds(first_date=datetime.date(2010, 1, 1), last_date=datetime.date(2020, 12, 31)) ``` -------------------------------- ### Get Package Version Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Access the package's version string. This is automatically generated and available. ```python from currency_converter import __version__ print(__version__) # e.g., "4.8.3" ``` -------------------------------- ### Internal Rate Structure Example Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Illustrates the nested dictionary structure used to store exchange rates by currency and date. Rates are expressed against the reference currency. ```python _rates = { 'USD': { date(2014, 3, 28): 1.3759, # 1 EUR = 1.3759 USD date(2014, 3, 27): 1.3758, date(2014, 3, 26): 1.3750, # ... more dates }, 'GBP': { date(2014, 3, 28): 0.8234, # 1 EUR = 0.8234 GBP date(2014, 3, 27): 0.8233, # ... more dates }, # ... more currencies } ``` -------------------------------- ### Load Currency Data from Single Day ECB URL Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Initialize the CurrencyConverter with the URL for the single latest day's rates from the ECB. This is useful for getting the most recent data without the full history. ```python from currency_converter import SINGLE_DAY_ECB_URL, CurrencyConverter c = CurrencyConverter(SINGLE_DAY_ECB_URL) ``` -------------------------------- ### CurrencyConverter Initialization with Different Data Sources Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/configuration.md Demonstrates initializing the CurrencyConverter with various data sources. This includes using embedded historical and single-day files, downloading the latest full history, or downloading the latest single-day rates. ```python from currency_converter import ( CurrencyConverter, CURRENCY_FILE, ECB_URL, SINGLE_DAY_ECB_URL, SINGLE_DAY_CURRENCY_FILE, ) # Use embedded historical data (included with package, may be outdated) c1 = CurrencyConverter(CURRENCY_FILE) # Use embedded single-day data (included with package, may be outdated) c2 = CurrencyConverter(SINGLE_DAY_CURRENCY_FILE) # Download latest full history (always up-to-date, first download slower) c3 = CurrencyConverter(ECB_URL) # Download latest single-day (latest rates, smallest data) c4 = CurrencyConverter(SINGLE_DAY_ECB_URL) ``` -------------------------------- ### Validate Object for S3CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md This example provides a helper function to validate if an object has the required 'get_contents_as_string()' method before passing it to S3CurrencyConverter, raising a ValueError for invalid objects. ```python from currency_converter import S3CurrencyConverter def create_s3_converter(obj): # Validate object has required method if not hasattr(obj, 'get_contents_as_string'): raise ValueError( f"Object must have 'get_contents_as_string()' method. " f"Got {type(obj).__name__}" ) return S3CurrencyConverter(obj) # Test with invalid object try: c = create_s3_converter("string") except ValueError as e: print(f"Invalid object: {e}") ``` -------------------------------- ### Initialize CurrencyConverter with Decimal Option Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Use the `decimal=True` option for exact conversions with `decimal.Decimal`. This may increase load times. ```python >>> c = CurrencyConverter(decimal=True) >>> c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) Decimal('129.100') ``` -------------------------------- ### Advanced Internal Utilities for Currency Data Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Provides examples of using internal utility functions for parsing dates, generating date ranges, and extracting data from ZIP files. ```python from currency_converter.currency_converter import ( parse_date, list_dates_between, get_lines_from_zip, memoize, Bounds, ) from datetime import date # Parse ECB date format d = parse_date("2014-03-21") # Generate date range dates = list_dates_between(date(2014, 1, 1), date(2014, 12, 31)) # Extract lines from ZIP file with open('rates.zip', 'rb') as f: for line in get_lines_from_zip(f.read()): print(line) ``` -------------------------------- ### Download and Use Daily ECB Data Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst This snippet demonstrates how to download the ECB currency data zip file only if it doesn't exist for the current day, and then use it to initialize the CurrencyConverter. This ensures you have up-to-date data without redundant downloads. ```python import os.path as op import urllib.request from datetime import date from currency_converter import ECB_URL, CurrencyConverter filename = f"ecb_{date.today():%Y%m%d}.zip" if not op.isfile(filename): urllib.request.urlretrieve(ECB_URL, filename) c = CurrencyConverter(filename) ``` -------------------------------- ### Retrieving and Searching Supported Currencies with CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Shows how to access the set of all supported currencies and how to search for currencies based on a prefix. It also demonstrates how to list currency bounds (first and last available dates). ```python from currency_converter import CurrencyConverter c = CurrencyConverter() # Get all available currencies print(c.currencies) # {'EUR', 'USD', 'GBP', 'JPY', ...} # Search for currency by prefix search_term = 'US' matching = [curr for curr in c.currencies if search_term in curr] print(matching) # ['USD'] # List with date ranges for curr in sorted(c.currencies): first, last = c.bounds[curr] print(f"{curr}: {first} to {last}") ``` -------------------------------- ### Command-line Currency Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Use the command-line tool to perform quick currency conversions. Specify the amount, source currency, and target currency. ```bash $ currency_converter 100 USD --to EUR 100.000 USD = 87.512 EUR on 2016-05-06 ``` -------------------------------- ### Instantiate S3CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/S3CurrencyConverter.md Instantiate S3CurrencyConverter with an S3 key object. The currency_file must provide a `get_contents_as_string()` method. Additional keyword arguments are passed to the parent class for configuration. ```python from currency_converter import S3CurrencyConverter import boto from datetime import date # Connect to S3 and get a key conn = boto.connect_s3() bucket = conn.get_bucket('my-bucket') key = bucket.get_key('path/to/eurofxref-hist.zip') # Create S3-backed converter c = S3CurrencyConverter(key) # Use it like a normal CurrencyConverter result = c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(result) # 129.1 # With fallback options c = S3CurrencyConverter( key, fallback_on_missing_rate=True, fallback_on_wrong_date=True, decimal=True ) result = c.convert(100, 'USD', date=date(2010, 11, 21)) ``` -------------------------------- ### ECB CSV Data Format Example Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Illustrates the comma-separated values format used by the European Central Bank for currency exchange rates. The first column is the date, followed by currency codes and their rates relative to EUR. ```csv Date,USD,JPY,BGN,CYP,CZK,... 2014-03-28,1.3759,140.9,1.9558,0.585,27.423,... 2014-03-27,1.3758,140.8,1.9557,0.585,27.422,... ``` -------------------------------- ### Load Custom Currency File Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Initialize the CurrencyConverter with a path to a custom CSV file containing currency exchange rates, provided it follows the ECB format. ```python from currency_converter import CurrencyConverter c = CurrencyConverter('./path/to/currency/file.csv') ``` -------------------------------- ### Correct S3 Usage for S3CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Illustrates the correct way to instantiate S3CurrencyConverter by providing a boto S3 key object as the 'currency_file' argument. It also shows how to set optional parameters for fallback behavior and decimal precision. ```python from currency_converter import S3CurrencyConverter import boto # Get S3 key object conn = boto.connect_s3() bucket = conn.get_bucket('my-bucket') key = bucket.get_key('rates/eurofxref-hist.zip') # Provide required currency_file argument c = S3CurrencyConverter(key) # Optional: provide additional parameters c = S3CurrencyConverter( key, fallback_on_missing_rate=True, fallback_on_wrong_date=True, decimal=True ) ``` -------------------------------- ### Initialize CurrencyConverter Object Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Create an instance of the CurrencyConverter class to begin performing conversions. This object should be created once. ```python from currency_converter import CurrencyConverter c = CurrencyConverter() ``` -------------------------------- ### Load Currency Data from ECB URL Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Initialize the CurrencyConverter with the European Central Bank's historical rates URL for up-to-date data. This downloads the full history. ```python from currency_converter import ECB_URL, CurrencyConverter c = CurrencyConverter(ECB_URL) ``` -------------------------------- ### load_file() Method Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Loads currency exchange rate data from a specified file path. ```APIDOC ## load_file() ### Description Loads historical currency exchange rate data from a file. The file format is expected to be CSV. ### Method load_file(file_path, file_type='csv') ### Parameters - **file_path** (str) - The path to the data file. - **file_type** (str, optional) - The type of the file. Defaults to 'csv'. ### Response None. This method modifies the internal state of the converter. ``` -------------------------------- ### Expose Public API from __init__.py Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md This snippet shows how the main currency converter package re-exports key components for its public interface. It includes the main class, an S3 variant, a custom exception, and various constants related to data sources. ```python from currency_converter import ( CurrencyConverter, # Main class for currency conversion S3CurrencyConverter, # S3-backed variant RateNotFoundError, # Exception for missing rates CURRENCY_FILE, # Path to embedded historical rates ECB_URL, # URL to ECB historical rates SINGLE_DAY_CURRENCY_FILE, # Path to embedded single-day rates SINGLE_DAY_ECB_URL, # URL to ECB single-day rates ) ``` -------------------------------- ### Currency Conversion with Error Handling Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Shows how to handle potential RateNotFoundError exceptions during currency conversion. ```python from currency_converter import CurrencyConverter, RateNotFoundError from datetime import date c = CurrencyConverter() try: result = c.convert(100, 'BGN', date=date(2010, 11, 21)) except RateNotFoundError as e: print(f"Rate not found: {e}") ``` -------------------------------- ### CurrencyConverter Class Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/INDEX.txt Documentation for the main CurrencyConverter class, including its constructor, methods, and public attributes. ```APIDOC ## Class CurrencyConverter ### Description Represents a currency converter that can load exchange rates from files or lines and perform conversions. ### Constructor Initializes a new instance of the CurrencyConverter class. ### Methods #### convert(from_currency: str, to_currency: str, amount: float) -> float Converts an amount from one currency to another. #### load_file(file_path: str) Loads exchange rates from a specified file. #### load_lines(lines: list[str]) Loads exchange rates from a list of strings. ### Public Attributes - **currencies**: list[str] - A list of available currency codes. - **bounds**: Bounds - Information about the bounds of the exchange rates. ``` -------------------------------- ### CurrencyConverter Class Initialization Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Initializes the CurrencyConverter class. This is the primary entry point for creating a converter instance. ```APIDOC ## CurrencyConverter.__init__ ### Description Initializes the main converter class. This constructor sets up the necessary data structures for currency conversion. ### Method __init__ ### Parameters None explicitly documented in this section, refer to `load_file()` or `load_lines()` for data loading. ### Response An instance of the CurrencyConverter class. ``` -------------------------------- ### Catch FileNotFoundError Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Demonstrates how to catch FileNotFoundError when initializing CurrencyConverter with a non-existent local file. ```python from currency_converter import CurrencyConverter try: c = CurrencyConverter('./missing-file.csv') except FileNotFoundError as e: print(f"File error: {e}") # Output: "[Errno 2] No such file or directory: './missing-file.csv'" ``` -------------------------------- ### Custom Data Sources Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Configure the converter to use custom data sources, such as downloading the latest rates from the European Central Bank (ECB), loading from a local CSV file, or using a daily cached file. ```python from currency_converter import CurrencyConverter, ECB_URL from datetime import date # Download latest rates from ECB c = CurrencyConverter(ECB_URL) # Load from local file c = CurrencyConverter('./my-rates.csv') # Smart download with daily caching import os.path as op import urllib.request filename = f"ecb_{{date.today():%Y%m%d}}.zip" if not op.isfile(filename): urllib.request.urlretrieve(ECB_URL, filename) c = CurrencyConverter(filename) ``` -------------------------------- ### S3CurrencyConverter Constructor Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/S3CurrencyConverter.md Instantiates an S3CurrencyConverter. The currency_file parameter must be an object with a get_contents_as_string() method, typically a boto.s3.key.Key object. ```APIDOC ## S3CurrencyConverter Constructor ### Description Instantiate an S3CurrencyConverter. The currency_file parameter is required and must be an object that provides a `get_contents_as_string()` method, which is the interface used by the `boto.s3.key.Key` class. ### Parameters #### Path Parameters - **currency_file** (object) - Required - An S3 key-like object (e.g., boto.s3.key.Key) that provides a `get_contents_as_string()` method returning the CSV file contents as a string (bytes or str). #### Query Parameters - **kwargs** (dict) - Optional - Additional keyword arguments passed to the parent CurrencyConverter.__init__(), such as fallback_on_wrong_date, fallback_on_missing_rate, decimal, verbose, etc. ### Returns An S3CurrencyConverter instance with rates loaded from the S3 object. ### Raises - **TypeError**: If currency_file is not provided (parent __init__ expects it). - **AttributeError**: If currency_file does not have a `get_contents_as_string()` method. - **ValueError**: If the CSV format from S3 is invalid. ### Example ```python from currency_converter import S3CurrencyConverter import boto from datetime import date # Connect to S3 and get a key conn = boto.connect_s3() bucket = conn.get_bucket('my-bucket') key = bucket.get_key('path/to/eurofxref-hist.zip') # Create S3-backed converter c = S3CurrencyConverter(key) # Use it like a normal CurrencyConverter result = c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(result) # 129.1 # With fallback options c = S3CurrencyConverter( key, fallback_on_missing_rate=True, fallback_on_wrong_date=True, decimal=True ) result = c.convert(100, 'USD', date=date(2010, 11, 21)) ``` ``` -------------------------------- ### Handle Unsupported Currency Error Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/exceptions.md Demonstrates how to check for supported currencies before conversion or use a try-except block to catch ValueError when an unsupported currency code is provided. ```python from currency_converter import CurrencyConverter c = CurrencyConverter() # Check if currency is supported before converting if 'AAA' not in c.currencies: print("AAA is not supported") else: result = c.convert(100, 'AAA') # Or use try-except try: result = c.convert(100, 'AAA') except ValueError as e: print(f"Conversion failed: {e}") print(f"Available currencies: {sorted(c.currencies)}") ``` -------------------------------- ### Initializing with Custom NA Values Frozenset Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Illustrates how to initialize the CurrencyConverter with a custom frozenset of string values that should be interpreted as missing rates. This allows for flexible handling of various representations of missing data. ```python c = CurrencyConverter(na_values=frozenset(["", "N/A"])) print(c.na_values) # frozenset({'', 'N/A'}) ``` -------------------------------- ### S3 Integration for Currency Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Demonstrates using S3CurrencyConverter to fetch currency rates from an S3 bucket. ```python from currency_converter import S3CurrencyConverter import boto key = boto.connect_s3().get_bucket('bucket').get_key('rates.zip') c = S3CurrencyConverter(key) result = c.convert(100, 'EUR', 'USD') ``` -------------------------------- ### Handle FileNotFoundError and URLError Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/exceptions.md Demonstrates how to catch FileNotFoundError for missing local files and URLError for network connection failures when initializing CurrencyConverter. ```python from currency_converter import CurrencyConverter from urllib.error import URLError # Handle missing local file try: c = CurrencyConverter('./missing-file.csv') except FileNotFoundError: print("Currency file not found, using default") c = CurrencyConverter() # Handle URL connection failure try: c = CurrencyConverter('https://example.com/rates.zip') except URLError: print("Failed to download rates, using default") c = CurrencyConverter() ``` -------------------------------- ### Basic Currency Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Initialize the converter and perform basic currency conversions using the latest rates or rates from a specific date. You can also check available currencies and their bounds. ```python from currency_converter import CurrencyConverter from datetime import date # Initialize converter c = CurrencyConverter() # Convert to default currency (EUR) amount_eur = c.convert(100, 'USD') # Uses latest rate # Convert between two currencies on a specific date amount_eur = c.convert(100, 'USD', 'EUR', date=date(2014, 3, 28)) # Check available currencies print(c.currencies) print(c.bounds['USD']) ``` -------------------------------- ### Define Main CLI Function Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Defines the main entry point for the command-line interface. It handles argument parsing using argparse. ```python def main() -> int: ... ``` -------------------------------- ### Check Available Currencies and Handle Errors Source: https://github.com/alexprengere/currencyconverter/blob/master/README.rst Verify if a currency is supported using the `currencies` set. Attempting to convert an unsupported currency will raise a `ValueError`. ```python >>> c.currencies # doctest: +SKIP set(['SGD', 'CAD', 'SEK', 'GBP', ... >>> 'AAA' in c.currencies False >>> c.convert(100, 'AAA') Traceback (most recent call last): ValueError: AAA is not a supported currency ``` -------------------------------- ### Instantiate CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/CurrencyConverter.md Initialize the CurrencyConverter with various options. Defaults to using embedded ECB historical rates. Can be configured to fallback on missing rates or dates, use Decimal for precision, or load data from a specified file or URL. ```python from currency_converter import CurrencyConverter from datetime import date # Create converter with default embedded data c = CurrencyConverter() # Convert 100 EUR to USD on a specific date result = c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(result) # 129.1 # Create converter with fallback options c_fallback = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_wrong_date=True ) result = c_fallback.convert(100, 'BGN', date=date(2010, 11, 21)) print(result) # Uses interpolation for missing rate # Use Decimal for exact conversions c_decimal = CurrencyConverter(decimal=True) result = c_decimal.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(type(result).__name__) # Decimal ``` -------------------------------- ### Load Currency Data from S3 Key Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/S3CurrencyConverter.md The `load_file` method is overridden to fetch data using `get_contents_as_string()` from the provided S3 key object. This allows updating the converter with data from a different S3 location. ```python from currency_converter import S3CurrencyConverter import boto conn = boto.connect_s3() bucket = conn.get_bucket('my-bucket') # Load from one key key1 = bucket.get_key('historical/eurofxref-hist.zip') c = S3CurrencyConverter(key1) # Later, load from a different key key2 = bucket.get_key('latest/eurofxref.zip') c.load_file(key2) ``` -------------------------------- ### CurrencyConverter Constructor Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/CurrencyConverter.md Instantiate a CurrencyConverter. At init, loads historic currencies from the specified source. The internal data structure `_rates` is a dictionary with currencies as keys and {date: rate, ...} dictionaries as values. The `currencies` set contains all available currencies, and `bounds` is a dict of first and last available dates per currency. ```APIDOC ## CurrencyConverter Constructor ### Description Instantiate a CurrencyConverter. At init, loads historic currencies from the specified source. The internal data structure `_rates` is a dictionary with currencies as keys and {date: rate, ...} dictionaries as values. The `currencies` set contains all available currencies, and `bounds` is a dict of first and last available dates per currency. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | currency_file | str | No | CURRENCY_FILE | Path or URL to currency data source. Can be a local file path, or a URL starting with 'http://' or 'https://'. Defaults to the embedded ECB historical rates file. Pass None to skip loading. | | fallback_on_wrong_date | bool | No | False | If False, raises RateNotFoundError when dates are requested outside the data's range. If True, extrapolates by falling back to the first or last data point for dates before and after the range respectively. | | fallback_on_missing_rate | bool | No | False | If True, linearly interpolates missing rates using the two closest valid rates. Only affects dates within the source data's range. If False, raises RateNotFoundError when hitting a missing rate (e.g., on weekends or banking holidays). | | fallback_on_missing_rate_method | str | No | "linear_interpolation" | Method to fill missing rates. Accepted values: "linear_interpolation" or "last_known". | | ref_currency | str | No | "EUR" | Three-letter currency code for the reference currency that the source data is oriented towards. | | na_values | frozenset | No | frozenset(["", "N/A"]) | What to interpret as missing values in the source data. | | decimal | bool | No | False | If True, uses decimal.Decimal internally for exact conversions. Slows loading time by factor ~10. | | verbose | bool | No | False | If True, prints information about what is being done under the hood (missing rates, fallback operations). | ### Returns A CurrencyConverter instance with loaded rates, currencies set, and bounds dict. ### Raises | Error Type | Condition | |---|---| | ValueError | If fallback_on_missing_rate_method is not a recognized value. | | FileNotFoundError | If currency_file is a local path that does not exist. | | URLError | If currency_file is a URL and the connection fails. | ### Example ```python from currency_converter import CurrencyConverter from datetime import date # Create converter with default embedded data c = CurrencyConverter() # Convert 100 EUR to USD on a specific date result = c.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(result) # 129.1 # Create converter with fallback options c_fallback = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_wrong_date=True ) result = c_fallback.convert(100, 'BGN', date=date(2010, 11, 21)) print(result) # Uses interpolation for missing rate # Use Decimal for exact conversions c_decimal = CurrencyConverter(decimal=True) result = c_decimal.convert(100, 'EUR', 'USD', date=date(2013, 3, 21)) print(type(result).__name__) # Decimal ``` ``` -------------------------------- ### Standard Currency Conversion Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Demonstrates basic currency conversion using the CurrencyConverter class with a specified date. ```python from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter() result = c.convert(100, 'EUR', 'USD', date=date(2014, 3, 28)) ``` -------------------------------- ### Load Currency Data from File or URL Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/CurrencyConverter.md Loads currency data from a specified file path or URL. This method can be used to initialize the converter or reload data. It supports local files, HTTP/HTTPS URLs, and automatically detects .zip or CSV formats. ```python from currency_converter import CurrencyConverter, ECB_URL, SINGLE_DAY_ECB_URL import urllib.request from datetime import date import os.path as op # Load packaged data (might not be up to date) c = CurrencyConverter() # Load full history from ECB (up to date) c.load_file(ECB_URL) # Load only the latest available day c.load_file(SINGLE_DAY_ECB_URL) # Load custom CSV file c.load_file('./path/to/currency/file.csv') # Download once a day to avoid repeated downloads filename = f"ecb_{date.today():%Y%m%d}.zip" if not op.isfile(filename): urllib.request.urlretrieve(ECB_URL, filename) c.load_file(filename) ``` -------------------------------- ### Basic URLError Handling Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Demonstrates how to catch a URLError when initializing CurrencyConverter with an invalid URL. This is useful for basic error reporting. ```python from currency_converter import CurrencyConverter from urllib.error import URLError try: c = CurrencyConverter('https://example.com/invalid-url') except URLError as e: print(f"URL error: {e}") ``` -------------------------------- ### Float Conversion (Default) with CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Demonstrates initializing CurrencyConverter without the decimal parameter, resulting in float return types for conversions. This is suitable for general use where exact precision is not critical. ```python # Float conversion (default) c_float = CurrencyConverter(decimal=False) result: float = c_float.convert(100, 'EUR', 'USD') ``` -------------------------------- ### Handling Network Errors with Fallback Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Shows two strategies for handling network errors when downloading currency data. Strategy 1 attempts to download from a remote URL and falls back to embedded data if an error occurs. Strategy 2 demonstrates specifying a manual timeout for the download request. ```python from currency_converter import CurrencyConverter, ECB_URL from urllib.error import URLError import socket # Strategy 1: Try remote, fallback to local try: c = CurrencyConverter(ECB_URL) except (URLError, socket.timeout): print("Failed to download from ECB, using embedded data") c = CurrencyConverter() # Strategy 2: Specify timeout manually via custom code import urllib.request from currency_converter import CurrencyConverter try: with urllib.request.urlopen(ECB_URL, timeout=10) as response: data = response.read() c = CurrencyConverter(ECB_URL) except URLError as e: print(f"Download failed after timeout: {e}") c = CurrencyConverter() ``` -------------------------------- ### convert() Method Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Converts an amount from one currency to another using the loaded exchange rates. ```APIDOC ## convert() ### Description Converts a specified amount from a source currency to a target currency. It utilizes the exchange rates loaded into the converter instance. ### Method convert(amount, source_currency, target_currency, date=None, fallback_method='closest') ### Parameters - **amount** (float | Decimal) - The amount of money to convert. - **source_currency** (str) - The currency code to convert from. - **target_currency** (str) - The currency code to convert to. - **date** (date, optional) - The specific date for the exchange rate. Defaults to the latest available rate if not provided. - **fallback_method** (str, optional) - Method to use if the exact date rate is not found. Defaults to 'closest'. ### Response - **float | Decimal**: The converted amount in the target currency. ``` -------------------------------- ### Public API Imports Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md The currency_converter package exposes several key components directly for user import. These include the main converter classes, an exception for handling missing rates, and constants related to currency data sources. ```APIDOC ## Public API **Source:** `currency_converter/__init__.py` The currency_converter package exposes the following public interface: ```python from currency_converter import ( CurrencyConverter, # Main class for currency conversion S3CurrencyConverter, # S3-backed variant RateNotFoundError, # Exception for missing rates CURRENCY_FILE, # Path to embedded historical rates ECB_URL, # URL to ECB historical rates SINGLE_DAY_CURRENCY_FILE, # Path to embedded single-day rates SINGLE_DAY_ECB_URL, # URL to ECB single-day rates ) ``` ### Exported Symbols by Type **Classes:** - `CurrencyConverter` — Main currency converter with exchange rate data - `S3CurrencyConverter` — Subclass for loading from S3 **Exceptions:** - `RateNotFoundError` — Custom exception for missing rate data **Constants:** - `CURRENCY_FILE` — str, path to embedded eurofxref-hist.zip - `ECB_URL` — str, URL to download ECB historical rates - `SINGLE_DAY_CURRENCY_FILE` — str, path to embedded eurofxref.csv - `SINGLE_DAY_ECB_URL` — str, URL to download ECB latest rates **Also available (imported via __init__):** - `__version__` — Package version string (from _version module) ``` -------------------------------- ### Accessing Available Currencies Set Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Demonstrates how to access and check for the presence of currency codes in the immutable set of available currencies. The set includes the reference currency. ```python c = CurrencyConverter() print(type(c.currencies).__name__) # set print(c.currencies) # {'EUR', 'USD', 'GBP', 'JPY', ...} print('USD' in c.currencies) # True print(len(c.currencies)) # 42 ``` -------------------------------- ### Handling RateNotFoundError in Python Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/exceptions.md Demonstrates three approaches to handling RateNotFoundError: catching the exception with a try-except block, using fallback options during CurrencyConverter initialization to avoid the error, and checking currency bounds before attempting a conversion. ```python from currency_converter import CurrencyConverter, RateNotFoundError from datetime import date c = CurrencyConverter() # Approach 1: Catch and handle the error try: result = c.convert(100, 'BGN', date=date(2010, 11, 21)) except RateNotFoundError as e: print(f"Conversion failed: {e}") # Handle error (use fallback value, skip conversion, etc.) ``` ```python # Approach 2: Use fallback options to avoid the error c_with_fallback = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_wrong_date=True ) result = c_with_fallback.convert(100, 'BGN', date=date(2010, 11, 21)) print(result) # Uses interpolated rate, no error ``` ```python # Approach 3: Check bounds before converting if date(2010, 11, 21) >= c.bounds['BGN'].first_date and \ date(2010, 11, 21) <= c.bounds['BGN'].last_date: result = c.convert(100, 'BGN', date=date(2010, 11, 21)) else: print("Date outside BGN bounds") ``` -------------------------------- ### Strict Mode Conversion (Default) Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/configuration.md Demonstrates default strict mode behavior where conversions fail for weekends or dates outside the available data range, raising a RateNotFoundError. ```python from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter() # Raises RateNotFoundError for weekends try: c.convert(100, 'USD', date=date(2014, 3, 22)) # Saturday except Exception as e: print(type(e).__name__) # RateNotFoundError # Raises RateNotFoundError for dates outside bounds try: c.convert(100, 'EUR', 'USD', date=date(1986, 2, 2)) except Exception as e: print(type(e).__name__) # RateNotFoundError ``` -------------------------------- ### Handle Invalid Fallback Method Error Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/api-reference/exceptions.md Shows how to correctly initialize CurrencyConverter with valid fallback methods ('linear_interpolation' or 'last_known') and how a try-except block catches ValueError for invalid methods. ```python from currency_converter import CurrencyConverter # Valid methods c1 = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="linear_interpolation" ) c2 = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="last_known" ) # Invalid method raises ValueError try: c3 = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="nearest" ) except ValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Default CurrencyConverter Configuration Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/configuration.md Instantiate CurrencyConverter with default settings. This configuration uses embedded historical data and strict error handling for invalid dates or missing rates. ```python CurrencyConverter( currency_file=CURRENCY_FILE, # Embedded eurofxref-hist.zip fallback_on_wrong_date=False, # Strict: raise on invalid dates fallback_on_missing_rate=False, # Strict: raise on missing rates fallback_on_missing_rate_method="linear_interpolation", # (unused) ref_currency="EUR", # European Central Bank reference na_values=frozenset(["", "N/A"]), decimal=False, # Use float for speed verbose=False, # No debug output ) ``` -------------------------------- ### Accessing Currency Date Bounds Dictionary Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/types.md Shows how to retrieve and inspect the date ranges associated with specific currency codes from the dictionary of bounds. This includes accessing the first and last available dates for a currency. ```python c = CurrencyConverter() print(type(c.bounds).__name__) # dict print(type(c.bounds['USD']).__name__) # bounds print(c.bounds['USD'].first_date) # datetime.date(1999, 1, 4) print(c.bounds['EUR'].last_date) # datetime.date(2025, 12, 31) ``` -------------------------------- ### Handling File Errors with CurrencyConverter Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Provides multiple strategies for handling missing currency rate files, including pre-checking file existence, using try-except with fallbacks, and checking/downloading files. ```python from currency_converter import CurrencyConverter import os.path as op # Strategy 1: Check file before loading file_path = './rates.csv' if op.isfile(file_path): c = CurrencyConverter(file_path) else: print(f"File not found: {file_path}, using default") c = CurrencyConverter() # Uses embedded data # Strategy 2: Use try-except with fallback try: c = CurrencyConverter('./custom-rates.csv') except FileNotFoundError: print("Custom file not found, using embedded data") c = CurrencyConverter() # Strategy 3: Check and create/download if needed import urllib.request from datetime import date file_path = f"ecb_{date.today():%Y%m%d}.zip" if not op.isfile(file_path): try: from currency_converter import ECB_URL urllib.request.urlretrieve(ECB_URL, file_path) except Exception as e: print(f"Download failed: {e}, using embedded data") c = CurrencyConverter() else: c = CurrencyConverter(file_path) else: c = CurrencyConverter(file_path) ``` -------------------------------- ### Re-export Symbols in __init__.py Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/imports-and-exports.md Imports all public symbols from the main module and the version information into the package's top level. ```python from .currency_converter import * # Imports all __all__ symbols from ._version import __version__ # Also exports version ``` -------------------------------- ### Handling Invalid Fallback Methods Gracefully Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/errors.md Illustrates a pattern for handling user-provided fallback methods by validating them against a list of known valid methods. If invalid, it prints a message and defaults to a safe option. ```python from currency_converter import CurrencyConverter VALID_METHODS = ("linear_interpolation", "last_known") user_method = "nearest" # from config or user input if user_method not in VALID_METHODS: print(f"Invalid method '{user_method}'. Use: {VALID_METHODS}") user_method = "linear_interpolation" # fallback to default c = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method=user_method ) ``` -------------------------------- ### Handling Missing Rates Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/README.md Demonstrates how to handle missing currency rates. The strict mode raises a RateNotFoundError, while the permissive mode interpolates or extrapolates rates. ```python from currency_converter import CurrencyConverter, RateNotFoundError from datetime import date # Strict mode (default) - raises on missing data c_strict = CurrencyConverter() try: # Weekend - no rate available c_strict.convert(100, 'USD', date=date(2014, 3, 22)) except RateNotFoundError: print("Rate not available") # Permissive mode - interpolates or extrapolates c_permissive = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_wrong_date=True ) result = c_permissive.convert(100, 'USD', date=date(2014, 3, 22)) ``` -------------------------------- ### Last Known Rate Fallback Strategy Source: https://github.com/alexprengere/currencyconverter/blob/master/_autodocs/configuration.md Sets up the converter to use the last known available rate when a specific rate for a given date is missing, instead of interpolation. ```python from currency_converter import CurrencyConverter from datetime import date c = CurrencyConverter( fallback_on_missing_rate=True, fallback_on_missing_rate_method="last_known" ) # For missing dates, uses last available rate (not interpolated) result = c.convert(100, 'USD', date=date(2014, 3, 22)) ```