create dashboard update realtime table dataframe from an api
To upload files, please first save the app
import streamlit as st
import pandas as pd
import requests
import time
# Configure the page to use wide layout
st.set_page_config(
page_title="Realtime Dashboard",
layout="wide"
)
st.title("Realtime Data Dashboard")
# Function to fetch data from API
def fetch_data():
# Using a sample API that provides crypto prices
# NOTE: Using corsproxy.io because we're in a WASM environment. If running locally,
# you can remove the corsproxy.io prefix.
url = "https://corsproxy.io/?https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,dogecoin&vs_currencies=usd"
try:
response = requests.get(url)
data = response.json()
# Transform the data into a DataFrame
df = pd.DataFrame([
{
'Cryptocurrency': 'Bitcoin',
'Price (USD)': data['bitcoin']['usd'],
},
{
'Cryptocurrency': 'Ethereum',
'Price (USD)': data['ethereum']['usd'],
},
{
'Cryptocurrency': 'Dogecoin',
'Price (USD)': data['dogecoin']['usd'],
}
])
return df
except Exception as e:
st.error(f"Error fetching data: {str(e)}")
return None
# Create placeholder for the table
table_placeholder = st.empty()
# Add a refresh rate selector
refresh_interval = st.sidebar.slider(
"Refresh interval (seconds)",
min_value=1,
max_value=60,
value=5
)
st.sidebar.markdown("---")
st.sidebar.markdown("### About")
st.sidebar.markdown("This dashboard shows real-time cryptocurrency prices.")
st.sidebar.markdown("Data is fetched from CoinGecko API.")
# Initialize session state for auto refresh
if 'auto_refresh' not in st.session_state:
st.session_state.auto_refresh = True
# Auto refresh toggle
st.session_state.auto_refresh = st.sidebar.checkbox(
"Auto refresh",
value=True
)
# Main dashboard area
st.markdown("### Live Cryptocurrency Prices")
st.markdown("Data updates automatically based on the selected refresh interval.")
# Manual refresh button
if st.button("Refresh Data"):
df = fetch_data()
if df is not None:
table_placeholder.table(df)
# Continuous update loop
while st.session_state.auto_refresh:
df = fetch_data()
if df is not None:
table_placeholder.table(df)
time.sleep(refresh_interval)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?