dibend commited on
Commit
c66a623
·
verified ·
1 Parent(s): be224f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import matplotlib.pyplot as plt
3
+ import requests
4
+ import os
5
+ import datetime
6
+ import random
7
+ import time
8
+
9
+ # Set the base currency (USD) and available cryptocurrencies
10
+ base_currency = "USD"
11
+ cryptos = ["BTC", "ETH", "XMR", "ETC", "RVN", "KAS", "DOGE", "LTC"]
12
+ colors = ["red", "blue", "green", "orange", "purple", "yellow", "gold", "aqua", "fuchsia", "chartreuse", "coral", "maroon", "olive"]
13
+
14
+ # Retrieve API key from environment variables
15
+ api_key = os.getenv("CRYPTOCOMPARE_API_KEY")
16
+
17
+ def fetch_crypto_data(crypto):
18
+ """Fetches historical price data for the selected cryptocurrency."""
19
+ crypto_prices = []
20
+ crypto_dates = []
21
+ current_timestamp = int(time.time())
22
+ end_date = current_timestamp
23
+ limit = 365 # Max limit per API call
24
+ total_data_points = 0
25
+
26
+ while total_data_points < limit:
27
+ url = f"https://min-api.cryptocompare.com/data/v2/histoday?fsym={crypto}&tsym={base_currency}&limit={limit}&toTs={end_date}&api_key={api_key}"
28
+ response = requests.get(url)
29
+ data = response.json()
30
+
31
+ if "Data" not in data or "Data" not in data["Data"]:
32
+ return "Error fetching data. Please check API key and limits."
33
+
34
+ data_points = len(data["Data"]["Data"])
35
+ total_data_points += data_points
36
+ crypto_prices += [x["close"] for x in data["Data"]["Data"]]
37
+ crypto_dates += [x["time"] for x in data["Data"]["Data"]]
38
+ end_date = data["Data"]["Data"][-1]["time"] - 86400
39
+
40
+ crypto_dates = [datetime.datetime.fromtimestamp(x).strftime("%Y-%m-%d") for x in crypto_dates]
41
+ return crypto_dates, crypto_prices
42
+
43
+
44
+ def plot_crypto_price(crypto):
45
+ """Plots the historical price data for the selected cryptocurrency."""
46
+ crypto_dates, crypto_prices = fetch_crypto_data(crypto)
47
+
48
+ if isinstance(crypto_dates, str):
49
+ return crypto_dates # Return error message
50
+
51
+ plt.figure(figsize=(12, 6))
52
+ plt.xticks(ticks=range(0, len(crypto_dates), 7), labels=crypto_dates[::7], rotation=90)
53
+ color = random.choice(colors)
54
+ plt.plot(crypto_dates, crypto_prices, label=crypto, color=color)
55
+ plt.fill_between(crypto_dates, crypto_prices, alpha=0.5, color=color)
56
+ plt.xlabel("Date")
57
+ plt.ylabel("Price (USD)")
58
+ plt.title(f"{crypto} Price History")
59
+ plt.legend()
60
+ plt.grid()
61
+
62
+ plt.savefig("crypto_plot.png")
63
+ return "crypto_plot.png"
64
+
65
+ # Create Gradio Interface
66
+ demo = gr.Interface(
67
+ fn=plot_crypto_price,
68
+ inputs=gr.Dropdown(choices=cryptos, label="Select Cryptocurrency"),
69
+ outputs=gr.Image(type="file", label="Price Chart"),
70
+ title="Cryptocurrency Price Visualization",
71
+ description="Select a cryptocurrency to view its historical price data over the past year."
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()