Skip to content

Instantly share code, notes, and snippets.

@AnnMarieW
Created October 1, 2022 18:51
Show Gist options
  • Save AnnMarieW/320713c78ef69b0c0c190ff4b546dd06 to your computer and use it in GitHub Desktop.
Save AnnMarieW/320713c78ef69b0c0c190ff4b546dd06 to your computer and use it in GitHub Desktop.
Live crypto price updates in a Bootstrap Card
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import requests
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.icons.BOOTSTRAP])
def get_data(coin):
try:
api_url = (
f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids={coin}"
)
response = requests.get(api_url)
response_json = response.json()
return (
response_json[0]["name"],
response_json[0]["image"],
response_json[0]["current_price"],
response_json[0]["price_change_percentage_24h"],
)
except:
return None, None, 0, 0
def make_card(coin, img, price, change):
color = "text-danger" if change < 0 else "text-success"
icon = "bi bi-arrow-down" if change < 0 else "bi bi-arrow-up"
return dbc.Card(
[
html.H3([html.Img(src=img, height=35, className="me-1"), coin]),
html.H4(f"${price:,}"),
html.Div(
[f"{round(change, 2)}%", html.I(className=icon), " 24hr"],
className=color,
),
],
className="text-center text-nowrap",
)
coins = ["bitcoin", "ethereum", "binancecoin", "ripple"]
mention = html.A(
"Data from CoinGecko", href="https://www.coingecko.com/en/api", className="small"
)
interval = dcc.Interval(interval=30000) # update every 30 seconds
cards = html.Div()
app.layout = dbc.Container([interval, cards, mention])
@app.callback(Output(cards, "children"), Input(interval, "n_intervals"))
def update_cards(_):
# make a list of cards with updated prices
coin_cards = []
for coin in coins:
name, image, price, change = get_data(coin)
if name:
coin_cards.append(make_card(name, image, price, change))
# make the card layout
card_layout = dbc.Row(
[dbc.Col(card, md=3, align="stretch") for card in coin_cards],
class_name="my-2",
)
return card_layout
if __name__ == "__main__":
app.run_server(debug=True)
@AnnMarieW
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment