Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions Currency Script/src/api_handler.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import requests
import json

def get_exchange_data(api_url: str = "https://theratesapi.com/api/latest/") -> dict:
def get_exchange_data(api_url: str = "https://open.er-api.com/v6/latest") -> dict:
"""Fetch latest exchange data from the API."""
response = requests.get(api_url)
if response.status_code != 200:
raise Exception(f"API request failed with status {response.status_code}")

data = response.json()
return data # This includes 'base', 'date', and 'rates'
# Ensure response was successful
if data.get("result") != "success":
raise Exception(f"API returned error: {data.get('error-type', 'Unknown error')}")

return data # Includes 'base_code', 'time_last_update_utc', and 'rates'

# NOTE - for logging & debugging
if __name__ == "__main__":
exchange_data = get_exchange_data()
print("Base currency:", exchange_data["base"])
print("Date:", exchange_data["date"])
print("Base currency:", exchange_data["base_code"])
print("Date:", exchange_data["time_last_update_utc"])
print("Rates:", list(exchange_data["rates"].items())[:5])
77 changes: 45 additions & 32 deletions Currency Script/src/converter.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,52 @@
# TODO REVIEW AND ENSURE THE PURPOSE OF THIS MODULE IS TO CONVERT
# Python program to convert the currency
# of one country to that of another country

# Import the modules needed
import requests

class Currency_convertor:
# empty dict to store the conversion rates
rates = {}

def __init__(self, url):
data = requests.get(url).json()
# Extracting only the rates from the json data
"""
CurrencyConverter: Converts an amount from one currency to another using live exchange rates.
"""

from api_handler import get_exchange_data

class CurrencyConverter:
def __init__(self):
data = get_exchange_data()
self.rates = data["rates"]

# function to do a simple cross multiplication between
# the amount and the conversion rates
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
if from_currency != 'EUR':
amount = amount / self.rates[from_currency]
def convert(self, from_currency: str, to_currency: str, amount: float) -> float:
"""
Convert amount between two currencies.

Args:
from_currency: Source currency code (e.g., 'USD')
to_currency: Target currency code (e.g., 'AUD')
amount: Amount to convert

Returns:
Converted amount as float

Raises:
ValueError: If a currency code is invalid
"""
from_currency = from_currency.upper()
to_currency = to_currency.upper()

if from_currency not in self.rates or to_currency not in self.rates:
raise ValueError("Invalid currency code.")

# limiting the precision to 2 decimal places
amount = round(amount * self.rates[to_currency], 2)
print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))
# Convert amount to base (EUR), then to target
amount_in_base = amount if from_currency == "EUR" else amount / self.rates[from_currency]
converted_amount = round(amount_in_base * self.rates[to_currency], 2)
return converted_amount

# Driver code
# --- DEBUG / MANUAL TEST ---
if __name__ == "__main__":
print("Running manual test for CurrencyConverter...\n")

YOUR_ACCESS_KEY = 'YOUR_ACCESS_KEY_HERE' # Define your access key
url = f'http://data.fixer.io/api/latest?access_key={YOUR_ACCESS_KEY}' # Use f-string for cleaner concatenation
c = Currency_convertor(url)

from_country = input("From Country (currency code): ")
to_country = input("To Country (currency code): ")
amount = float(input("Amount: ")) # Use float for decimal support
converter = CurrencyConverter()
from_cur = "USD"
to_cur = "AUD"
amt = 100.0

c.convert(from_country, to_country, amount)
print(f"Converting {amt} {from_cur} to {to_cur}...")
try:
result = converter.convert(from_cur, to_cur, amt)
print(f"{amt} {from_cur} = {result} {to_cur}")
except ValueError as e:
print("Error during conversion:", e)