Y4SH commited on
Commit
c3c01b7
·
verified ·
1 Parent(s): 33b26eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -30
app.py CHANGED
@@ -1,55 +1,85 @@
1
  import streamlit as st
2
  import requests
 
 
 
3
  import os
4
 
5
- # Streamlit Page Configuration
6
- st.set_page_config(page_title="Currency Converter", page_icon="💱", layout="centered")
 
7
 
8
- # Title & Description
9
- st.title("💱 Currency Converter")
10
- st.write("Convert currencies in real-time using the latest exchange rates.")
11
 
12
- # Get API Key Securely
13
- API_KEY = os.getenv("API_KEY") # Fetch from Hugging Face Secrets
14
 
15
- # Base API URL
16
- BASE_URL = "https://api.apilayer.com/exchangerates_data/latest"
17
 
18
- # Fetch List of Available Currencies
19
- @st.cache_data # Cache to avoid multiple API calls
20
  def get_currencies():
21
  url = f"{BASE_URL}?apikey={API_KEY}"
22
  response = requests.get(url).json()
23
-
24
  if "rates" in response:
25
- return sorted(response["rates"].keys()) # Sorted list of currencies
26
- else:
27
- st.error("⚠️ Unable to fetch currency list. Check API key.")
28
- return []
29
 
30
- # Load Currency Options
31
  currencies = get_currencies()
32
 
33
- # User Inputs
34
- amount = st.number_input("Enter Amount:", min_value=0.01, step=0.01)
35
- from_currency = st.selectbox("From Currency", currencies, index=currencies.index("USD"))
36
- to_currency = st.selectbox("To Currency", currencies, index=currencies.index("INR"))
 
 
 
37
 
38
- # Conversion Function
39
  def convert_currency(amount, from_currency, to_currency):
40
  url = f"{BASE_URL}?base={from_currency}&apikey={API_KEY}"
41
  response = requests.get(url).json()
42
-
43
  if "rates" in response and to_currency in response["rates"]:
44
- converted_amount = amount * response["rates"][to_currency]
45
- return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
 
46
  else:
47
- return "⚠️ Error: Unable to fetch exchange rates."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # Convert Button
50
- if st.button("Convert"):
51
  if from_currency == to_currency:
52
- st.warning("Please select different currencies! 🚀")
53
  else:
54
- result = convert_currency(amount, from_currency, to_currency)
55
- st.success(f"**{result}**") # Bold Black Output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import requests
3
+ import plotly.graph_objects as go
4
+ from datetime import datetime, timedelta
5
+ from dotenv import load_dotenv
6
  import os
7
 
8
+ # Load API Key from .env
9
+ load_dotenv()
10
+ API_KEY = os.getenv("API_KEY") # Fetch from .env file
11
 
12
+ # API Endpoints
13
+ BASE_URL = "https://api.apilayer.com/exchangerates_data/latest"
14
+ HISTORICAL_URL = "https://api.apilayer.com/exchangerates_data/timeseries"
15
 
16
+ # Streamlit Page Configuration
17
+ st.set_page_config(page_title="💱 Currency Converter", page_icon="💰", layout="wide")
18
 
19
+ # Title
20
+ st.title("💱 Currency Converter")
21
 
22
+ # Fetch available currencies
23
+ @st.cache_data
24
  def get_currencies():
25
  url = f"{BASE_URL}?apikey={API_KEY}"
26
  response = requests.get(url).json()
 
27
  if "rates" in response:
28
+ return sorted(response["rates"].keys())
29
+ return ["USD", "INR", "EUR", "GBP", "CAD"] # Default if API fails
 
 
30
 
 
31
  currencies = get_currencies()
32
 
33
+ # Input Section
34
+ col1, col2 = st.columns(2)
35
+ with col1:
36
+ amount = st.number_input("Enter Amount:", min_value=0.01, step=0.01)
37
+ with col2:
38
+ from_currency = st.selectbox("From Currency", currencies, index=currencies.index("USD"))
39
+ to_currency = st.selectbox("To Currency", currencies, index=currencies.index("INR"))
40
 
41
+ # Function to Convert Currency
42
  def convert_currency(amount, from_currency, to_currency):
43
  url = f"{BASE_URL}?base={from_currency}&apikey={API_KEY}"
44
  response = requests.get(url).json()
 
45
  if "rates" in response and to_currency in response["rates"]:
46
+ exchange_rate = response["rates"][to_currency]
47
+ converted_amount = amount * exchange_rate
48
+ return converted_amount, exchange_rate
49
  else:
50
+ return None, None
51
+
52
+ # Fetch Historical Data
53
+ def get_historical_data(from_currency, to_currency):
54
+ end_date = datetime.today().strftime("%Y-%m-%d")
55
+ start_date = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
56
+
57
+ url = f"{HISTORICAL_URL}?apikey={API_KEY}&start_date={start_date}&end_date={end_date}&base={from_currency}&symbols={to_currency}"
58
+ response = requests.get(url).json()
59
+
60
+ if "rates" in response:
61
+ dates = sorted(response["rates"].keys()) # Sort dates
62
+ rates = [response["rates"][date][to_currency] for date in dates]
63
+ return dates, rates
64
+ return [], []
65
 
66
  # Convert Button
67
+ if st.button("Convert Now"):
68
  if from_currency == to_currency:
69
+ st.warning("⚠️ Please select different currencies!")
70
  else:
71
+ converted_amount, exchange_rate = convert_currency(amount, from_currency, to_currency)
72
+ if converted_amount:
73
+ # Black Font Output
74
+ st.write(f"### 💵 {amount} {from_currency} = **{converted_amount:.2f} {to_currency}**")
75
+ st.write(f"#### 📈 Exchange Rate: **{exchange_rate:.4f}**")
76
+
77
+ # Display Graph
78
+ dates, rates = get_historical_data(from_currency, to_currency)
79
+ if dates:
80
+ fig = go.Figure()
81
+ fig.add_trace(go.Scatter(x=dates, y=rates, mode="lines+markers", name=f"{from_currency} to {to_currency}"))
82
+ fig.update_layout(title=f"{from_currency} to {to_currency} Exchange Rate (Last 30 Days)", xaxis_title="Date", yaxis_title="Exchange Rate")
83
+ st.plotly_chart(fig)
84
+ else:
85
+ st.error("❌ Error: Unable to fetch exchange rates.")