From a741b181f57e67f9841eb927b2c3f7fe0db1f787 Mon Sep 17 00:00:00 2001 From: ChuckBuilds <33324927+ChuckBuilds@users.noreply.github.com> Date: Fri, 11 Apr 2025 11:30:49 -0500 Subject: [PATCH] Redesign stock display: Add scrolling animation with logo, symbol, mini chart, and stacked price info --- src/stock_manager.py | 179 ++++++++++++++++++++++++++++++++----------- 1 file changed, 135 insertions(+), 44 deletions(-) diff --git a/src/stock_manager.py b/src/stock_manager.py index efc650e9..03ef56a8 100644 --- a/src/stock_manager.py +++ b/src/stock_manager.py @@ -8,6 +8,7 @@ from datetime import datetime import os import urllib.parse import re +from PIL import Image, ImageDraw # Configure logging logging.basicConfig(level=logging.INFO) @@ -21,7 +22,20 @@ class StockManager: self.last_update = 0 self.stock_data = {} self.current_stock_index = 0 - self.display_mode = 'info' # 'info' or 'chart' + self.scroll_position = 0 + self.cached_text_image = None + self.cached_text = None + + # Get scroll settings from config with faster defaults + self.scroll_speed = self.stocks_config.get('scroll_speed', 1) + self.scroll_delay = self.stocks_config.get('scroll_delay', 0.001) + + # Initialize frame rate tracking + self.frame_count = 0 + self.last_frame_time = time.time() + self.last_fps_log_time = time.time() + self.frame_times = [] + self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } @@ -275,8 +289,105 @@ class StockManager: else: logger.error("Failed to fetch data for any configured stocks") + def _create_stock_display(self, symbol: str, data: Dict[str, Any]) -> Image.Image: + """Create an image containing the stock information for efficient scrolling.""" + width = self.display_manager.matrix.width + height = self.display_manager.matrix.height + + # Create a new image with black background + display_image = Image.new('RGB', (width, height), (0, 0, 0)) + draw = ImageDraw.Draw(display_image) + + # Get stock color + color = self._get_stock_color(symbol) + + # Draw stock logo (placeholder for now - we'll use a simple icon) + logo_text = "📈" if data.get('change', 0) >= 0 else "📉" + bbox = draw.textbbox((0, 0), logo_text, font=self.display_manager.small_font) + logo_width = bbox[2] - bbox[0] + logo_height = bbox[3] - bbox[1] + logo_y = (height - logo_height) // 2 + draw.text((2, logo_y), logo_text, font=self.display_manager.small_font, fill=color) + + # Draw symbol + symbol_text = symbol + bbox = draw.textbbox((0, 0), symbol_text, font=self.display_manager.small_font) + symbol_width = bbox[2] - bbox[0] + symbol_height = bbox[3] - bbox[1] + symbol_x = (width - symbol_width) // 2 + symbol_y = (height - symbol_height) // 2 + draw.text((symbol_x, symbol_y), symbol_text, font=self.display_manager.small_font, fill=(255, 255, 255)) + + # Draw mini chart + if data.get('price_history'): + chart_width = width // 4 + chart_height = height // 3 + chart_x = width - chart_width - 2 + chart_y = (height - chart_height) // 2 + + # Get price data for chart + prices = [p['price'] for p in data['price_history']] + if prices: + min_price = min(prices) + max_price = max(prices) + price_range = max_price - min_price + + if price_range > 0: + points = [] + for i, price in enumerate(prices): + x = chart_x + int((i / len(prices)) * chart_width) + y = chart_y + chart_height - int(((price - min_price) / price_range) * chart_height) + points.append((x, y)) + + # Draw lines between points + for i in range(len(points) - 1): + draw.line([points[i], points[i + 1]], fill=color, width=1) + + # Draw price and change below + price_text = f"${data['price']:.2f}" + change_text = f"({data['change']:+.1f}%)" + + # Draw price + bbox = draw.textbbox((0, 0), price_text, font=self.display_manager.small_font) + price_width = bbox[2] - bbox[0] + price_x = (width - price_width) // 2 + draw.text((price_x, height - 20), price_text, font=self.display_manager.small_font, fill=color) + + # Draw change + bbox = draw.textbbox((0, 0), change_text, font=self.display_manager.small_font) + change_width = bbox[2] - bbox[0] + change_x = (width - change_width) // 2 + draw.text((change_x, height - 10), change_text, font=self.display_manager.small_font, fill=color) + + return display_image + + def _log_frame_rate(self): + """Log frame rate statistics.""" + current_time = time.time() + + # Calculate instantaneous frame time + frame_time = current_time - self.last_frame_time + self.frame_times.append(frame_time) + + # Keep only last 100 frames for average + if len(self.frame_times) > 100: + self.frame_times.pop(0) + + # Log FPS every second + if current_time - self.last_fps_log_time >= 1.0: + avg_frame_time = sum(self.frame_times) / len(self.frame_times) + avg_fps = 1.0 / avg_frame_time if avg_frame_time > 0 else 0 + instant_fps = 1.0 / frame_time if frame_time > 0 else 0 + + logger.info(f"Frame stats - Avg FPS: {avg_fps:.1f}, Current FPS: {instant_fps:.1f}, Frame time: {frame_time*1000:.2f}ms") + self.last_fps_log_time = current_time + self.frame_count = 0 + + self.last_frame_time = current_time + self.frame_count += 1 + def display_stocks(self, force_clear: bool = False): - """Display stock information on the LED matrix.""" + """Display stock information with scrolling animation.""" if not self.stocks_config.get('enabled', False): return @@ -296,51 +407,31 @@ class StockManager: current_symbol = symbols[self.current_stock_index] data = self.stock_data[current_symbol] - # Toggle between info and chart display - if self.display_mode == 'info': - # Clear the display + # Create the display image if needed + if self.cached_text_image is None or self.cached_text != current_symbol: + self.cached_text_image = self._create_stock_display(current_symbol, data) + self.cached_text = current_symbol + + # Clear the display if requested + if force_clear: self.display_manager.clear() - - # Draw the stock symbol at the top with regular font - self.display_manager.draw_text( - data['symbol'], - y=2, # Near top - color=(255, 255, 255) # White for symbol - ) - - # Draw the price in the middle with small font - price_text = f"${data['price']:.2f}" - self.display_manager.draw_text( - price_text, - y=14, # Middle - color=(0, 255, 0) if data['change'] >= 0 else (255, 0, 0), # Green for up, red for down - small_font=True # Use small font - ) - - # Draw the change percentage at the bottom with small font - change_text = f"({data['change']:+.1f}%)" - self.display_manager.draw_text( - change_text, - y=24, # Near bottom - color=(0, 255, 0) if data['change'] >= 0 else (255, 0, 0), # Green for up, red for down - small_font=True # Use small font - ) - - # Update the display - self.display_manager.update_display() - - # Switch to chart mode next time - self.display_mode = 'chart' - else: # chart mode - self._draw_chart(current_symbol, data) - # Switch back to info mode next time - self.display_mode = 'info' + self.scroll_position = 0 - # Add a delay to make each display visible - time.sleep(3) + # Copy the cached image to the display + self.display_manager.image.paste(self.cached_text_image, (0, 0)) + self.display_manager.update_display() - # Move to next stock for next update - self.current_stock_index = (self.current_stock_index + 1) % len(symbols) + # Log frame rate + self._log_frame_rate() + + # Add a small delay between frames + time.sleep(self.scroll_delay) + + # Move to next stock after a delay + if time.time() - self.last_update > 5: # Show each stock for 5 seconds + self.current_stock_index = (self.current_stock_index + 1) % len(symbols) + self.last_update = time.time() + self.cached_text_image = None # Force recreation of display for next stock # If we've shown all stocks, signal completion by returning True return self.current_stock_index == 0 \ No newline at end of file