30 – Real-World Python Projects – Real-time Currency Converter

🎯 Project Objective

To build a Python-based Currency Converter that fetches real-time exchange rates using an API and allows users to convert between currencies instantly.

Key Concepts:

  • Working with APIs (live exchange rates)
  • Handling JSON data
  • Building a simple GUI with Tkinter (optional)
  • Performing accurate currency calculations

🧩 1. Project Overview

The Real-Time Currency Converter fetches the latest exchange rates (e.g., USD β†’ EUR, INR β†’ GBP) and converts any given amount.
It’s useful for:

  • Travelers checking exchange rates
  • E-commerce websites displaying multi-currency prices
  • Finance/budget tracking apps

βš™οΈ 2. Libraries Used (Auto Installer)

import os, sys, subprocess
def install(pkg):
    subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])

for pkg in ["requests", "tkintertable"]:
    try:
        __import__(pkg)
    except ImportError:
        install(pkg)

You’ll mainly need requests (for API calls) and optionally tkinter (for GUI).


🌍 3. Free Exchange Rate API (Example)

Use the ExchangeRate API (no key needed):

https://api.exchangerate-api.com/v4/latest/USD

This returns a JSON file like:

{
  "base": "USD",
  "date": "2025-10-26",
  "rates": {
    "EUR": 0.93,
    "INR": 83.12,
    "GBP": 0.78,
    "JPY": 149.23
  }
}

πŸ’» 4. Real-Time Currency Converter (CLI Version)

import requests

def get_exchange_rate(base_currency, target_currency):
    url = f"https://api.exchangerate-api.com/v4/latest/{base_currency.upper()}"
    response = requests.get(url)
    data = response.json()
    if "rates" not in data:
        print("Error fetching exchange rates!")
        return None
    rates = data["rates"]
    if target_currency.upper() not in rates:
        print("Currency not supported.")
        return None
    return rates[target_currency.upper()]

def convert_currency(amount, base, target):
    rate = get_exchange_rate(base, target)
    if rate:
        converted = amount * rate
        print(f"πŸ’± {amount} {base.upper()} = {converted:.2f} {target.upper()} (Rate: {rate})")
        return converted
    return None

# Example usage
convert_currency(100, "USD", "INR")
convert_currency(500, "EUR", "GBP")

βœ… Output Example

πŸ’± 100 USD = 8312.00 INR (Rate: 83.12)
πŸ’± 500 EUR = 390.00 GBP (Rate: 0.78)

πŸͺŸ 5. GUI Version using Tkinter

import tkinter as tk
from tkinter import ttk, messagebox
import requests

def convert():
    base = base_currency.get()
    target = target_currency.get()
    amount = float(amount_entry.get())
    url = f"https://api.exchangerate-api.com/v4/latest/{base}"
    data = requests.get(url).json()
    rate = data["rates"].get(target)
    if rate:
        result = amount * rate
        result_label.config(text=f"{amount} {base} = {result:.2f} {target}")
    else:
        messagebox.showerror("Error", "Currency not supported")

root = tk.Tk()
root.title("Real-Time Currency Converter")
root.geometry("350x250")

tk.Label(root, text="Amount").pack()
amount_entry = tk.Entry(root)
amount_entry.pack()

tk.Label(root, text="From Currency").pack()
base_currency = ttk.Combobox(root, values=["USD", "INR", "EUR", "GBP", "JPY"])
base_currency.current(0)
base_currency.pack()

tk.Label(root, text="To Currency").pack()
target_currency = ttk.Combobox(root, values=["USD", "INR", "EUR", "GBP", "JPY"])
target_currency.current(1)
target_currency.pack()

tk.Button(root, text="Convert", command=convert).pack(pady=10)
result_label = tk.Label(root, text="Result will appear here", font=("Arial", 12))
result_label.pack()

root.mainloop()

βœ… GUI Output:
A small interactive window that lets you:

  • Choose base and target currencies
  • Enter an amount
  • Instantly see converted value fetched live

πŸ’‘ 6. Enhancement Ideas

FeatureDescription
πŸ“ˆ Rate HistoryStore rates daily using CSV or SQLite
🌐 Auto Detect CurrencyUse IP API to detect user’s local currency
πŸͺ™ Multi-Currency ConversionConvert to multiple currencies at once
πŸ“Š Graph ViewShow rate trends using matplotlib
πŸ”” AlertsNotify when rate crosses a threshold
πŸ’Ύ Offline CacheSave recent rates for offline mode

πŸ“Š 7. Add Historical Rates & Export

import pandas as pd
from datetime import datetime

def log_conversion(base, target, amount, result):
    log = pd.DataFrame([[datetime.now(), base, target, amount, result]],
                       columns=["Time", "Base", "Target", "Amount", "Converted"])
    if not os.path.exists("conversion_log.csv"):
        log.to_csv("conversion_log.csv", index=False)
    else:
        log.to_csv("conversion_log.csv", mode="a", header=False, index=False)

# Add inside convert_currency()
# log_conversion(base, target, amount, converted)

Export as Excel report:

df = pd.read_csv("conversion_log.csv")
df.to_excel("currency_conversion_report.xlsx", index=False)
print("πŸ“‚ Report exported to Excel.")

βœ… Summary

FeatureDescription
🌍 Real-time APILive rates using requests
πŸ’± ConversionAny two currencies
πŸ–₯️ GUITkinter-based converter
πŸ’Ύ LoggingSave all conversions to CSV
πŸ“ˆ ExtendableAdd alerts, trends, history

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *