Skip to content

Instantly share code, notes, and snippets.

@jackpa99
Created February 8, 2025 07:28
Show Gist options
  • Save jackpa99/095301e05ae3d883f048c0c61b3fd5e1 to your computer and use it in GitHub Desktop.
Save jackpa99/095301e05ae3d883f048c0c61b3fd5e1 to your computer and use it in GitHub Desktop.
Utilities
import requests
import tkinter as tk
from time import sleep
from datetime import datetime
import logging
# Setup logging
logging.basicConfig(filename='bitcoin_price.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def get_bitcoin_price():
url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'bitcoin' in data and 'usd' in data['bitcoin']:
return data['bitcoin']['usd']
else:
logging.error(f"Missing 'bitcoin' or 'usd' key in response: {data}")
return None
else:
logging.error(f"HTTP Error: {response.status_code}")
return None
except requests.RequestException as e:
logging.error(f"Request failed: {e}")
return None
def update_price_label():
price = get_bitcoin_price()
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if price is not None:
price_label.config(text=f"Bitcoin Price: ${price}\nRetrieved at: {current_time}")
else:
price_label.config(text=f"Error fetching price\nLast attempt: {current_time}")
# Update the price every 10 seconds
root.after(10000, update_price_label)
def on_closing():
logging.info("Application closed by user.")
root.destroy() # This will properly close the tkinter window and stop the app
root = tk.Tk()
root.title("Bitcoin Price Tracker")
# Make the window stay on top
root.attributes("-topmost", True)
price_label = tk.Label(root, text="Bitcoin Price: Loading...", font=("Helvetica", 24))
price_label.pack(pady=20)
# Call the on_closing function when the window is closed
root.protocol("WM_DELETE_WINDOW", on_closing)
update_price_label()
root.mainloop()
import yfinance as yf
import tkinter as tk
# List of stock tickers to track
TICKERS = ["GM", "F"]
REFRESH_INTERVAL = 30000 # 30 seconds
HISTORY_SLOTS = 120 # Keep history for 120 refreshes (2 hours)
# Store historical prices per ticker
price_history = {ticker: [] for ticker in TICKERS}
def fetch_prices():
"""Fetch stock prices for the given tickers."""
prices = {}
for ticker in TICKERS:
try:
stock = yf.Ticker(ticker)
data = stock.history(period="1d")
prices[ticker] = data['Close'].iloc[-1]
except Exception:
prices[ticker] = "*err" # Handle API fetch errors
return prices
def update_prices():
"""Update the stock prices on the GUI."""
prices = fetch_prices()
for ticker, price in prices.items():
# Maintain historical prices for the ticker
if price != "*err":
price_history[ticker].append(price)
if len(price_history[ticker]) > HISTORY_SLOTS:
price_history[ticker].pop(0)
# Display the current and historical prices
current_price = price
price_30m = f"~30m: ${price_history[ticker][60]:.2f}" if len(price_history[ticker]) > 60 else "~30m: N/A"
price_2h = f"~2h: ${price_history[ticker][120]:.2f}" if len(price_history[ticker]) > 120 else "~2h: N/A"
# Update label text
price_text = f"{ticker}: {current_price} {price_30m} {price_2h}"
price_labels[ticker].config(text=price_text)
# Schedule the next update
root.after(REFRESH_INTERVAL, update_prices)
# Create the main Tkinter window
root = tk.Tk()
root.title("Stock Price Viewer")
# Ensure the window stays on top and allows resizing
root.attributes("-topmost", True)
root.overrideredirect(False) # Removes default window decorations (if set to True)
root.resizable(True, True)
# Add labels to display stock prices
price_labels = {}
for ticker in TICKERS:
label = tk.Label(root, text=f"{ticker}: Fetching...", font=("Arial", 14))
label.pack(pady=5)
price_labels[ticker] = label
# Make the window draggable by clicking anywhere
def start_drag(event):
root.x = event.x
root.y = event.y
def drag_window(event):
x = root.winfo_pointerx() - root.x
y = root.winfo_pointery() - root.y
root.geometry(f"+{x}+{y}")
root.bind("<Button-1>", start_drag)
root.bind("<B1-Motion>", drag_window)
# Initial price update and GUI loop
update_prices()
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment