create an app that tracks the live price of selected cryptocurrencies using an API like CoinGecko.
Drop files here
or click to upload
import streamlit as st
import requests
import pandas as pd
import matplotlib.pyplot as plt
st.title("Crypto Price Tracker")
# Fetch price and volume data for top 10 cryptocurrencies from CoinGecko API
url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false"
response = requests.get(url)
crypto_data = response.json()
# Create a DataFrame from the API data
df = pd.DataFrame(crypto_data)
# Check if data was retrieved successfully
if not df.empty:
# Filter for columns we need and rename them
df = df[['id', 'name', 'current_price', 'market_cap', 'total_volume']]
df.columns = ['ID', 'Cryptocurrency', 'Price (USD)', 'Market Cap (USD)', 'Volume (24h)']
# Display a dropdown for cryptocurrency selection
crypto_names = df['Cryptocurrency'].tolist()
selected_crypto = st.selectbox("Select a Cryptocurrency from Top 10", crypto_names)
# Allow user to enter a custom cryptocurrency name
user_input = st.text_input("Or enter a cryptocurrency name")
# Determine the cryptocurrency to search for
if user_input.strip():
search_crypto = user_input.strip()
# Fetch the ID for the custom cryptocurrency
search_url = f"https://api.coingecko.com/api/v3/coins/{search_crypto.lower()}"
search_response = requests.get(search_url)
if search_response.status_code == 200:
search_data = search_response.json()
crypto_id = search_data['id']
selected_crypto_name = search_data['name']
selected_data = {
"Cryptocurrency": selected_crypto_name,
"Price (USD)": search_data['market_data']['current_price']['usd'],
"Market Cap (USD)": search_data['market_data']['market_cap']['usd'],
"Volume (24h)": search_data['market_data']['total_volume']['usd']
}
custom_search = True
else:
st.error("Cryptocurrency not found. Please enter a valid name.")
custom_search = False
else:
# Use the dropdown selection if no custom input is provided
crypto_id = df[df['Cryptocurrency'] == selected_crypto]['ID'].values[0]
selected_data = df[df['Cryptocurrency'] == selected_crypto].to_dict(orient="records")[0]
custom_search = False
# Display the selected cryptocurrency's details
if selected_data:
st.write("### Current Data")
st.write(pd.DataFrame([selected_data]).set_index('Cryptocurrency'))
# Fetch historical data for the selected cryptocurrency
history_url = f"https://api.coingecko.com/api/v3/coins/{crypto_id}/market_chart?vs_currency=usd&days=7"
history_response = requests.get(history_url)
history_data = history_response.json()
# Process historical price data if available
if 'prices' in history_data:
prices = history_data['prices']
dates = [pd.to_datetime(price[0], unit='ms') for price in prices]
price_values = [price[1] for price in prices]
# Create a DataFrame for plotting
history_df = pd.DataFrame({
'Date': dates,
'Price (USD)': price_values
})
# Display the slider to select the date range
min_date, max_date = history_df['Date'].min(), history_df['Date'].max()
date_range = st.slider(
"Select Date Range",
min_value=min_date,
max_value=max_date,
value=(min_date, max_date),
format="MM/DD"
)
# Filter the DataFrame based on the selected date range
filtered_history_df = history_df[(history_df['Date'] >= date_range[0]) & (history_df['Date'] <= date_range[1])]
# Plot the historical prices within the selected date range
st.write("### Price History (Last 7 Days)")
fig, ax = plt.subplots()
ax.plot(filtered_history_df['Date'], filtered_history_df['Price (USD)'], color='blue')
ax.set_title(f"{selected_data['Cryptocurrency']} Price Over the Selected Range")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
st.pyplot(fig)
else:
st.write("Historical price data not available for this cryptocurrency.")
else:
st.write("Could not retrieve crypto data. Please try again.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?