Spaces:
Sleeping
Sleeping
| """ | |
| 🇬🇧 Module: visualization.py | |
| Purpose: Contains visualization utilities such as plotting charts for portfolio analytics (e.g., Alpha vs BTC). | |
| 🇷🇺 Модуль: visualization.py | |
| Назначение: содержит функции визуализации данных, включая построение графиков портфелей (например, Alpha к BTC). | |
| """ | |
| import matplotlib.pyplot as plt | |
| import requests | |
| from typing import Optional | |
| from config import EXTERNAL_API_URL, DEBUG | |
| def build_alpha_chart(portfolio_id: str) -> Optional[plt.Figure]: | |
| """Fetch alphaBTC series and build a matplotlib figure.""" | |
| url = ( | |
| f"{EXTERNAL_API_URL}/portfolio/get?" | |
| f"portfolioId={portfolio_id}&extended=1&declaration=1&step=day&lang=en&incViews=1" | |
| ) | |
| headers = {"User-Agent": "Mozilla/5.0", "Accept": "application/json"} | |
| try: | |
| response = requests.get(url, headers=headers) | |
| if DEBUG: | |
| print(f"[DEBUG] GET {url} -> {response.status_code}") | |
| print(f"[DEBUG] Response preview: {response.text[:200]}...") | |
| response.raise_for_status() | |
| data = response.json() | |
| extended = data.get("data", {}).get("extended", {}) | |
| alpha_data = extended.get("alphaBTC", []) | |
| if not alpha_data or not isinstance(alpha_data, list): | |
| print("[WARN] No alphaBTC data found.") | |
| return None | |
| values = [item.get("value", 0) for item in alpha_data] | |
| indices = list(range(len(values))) | |
| # Create plot | |
| fig, ax = plt.subplots(figsize=(12, 6)) | |
| ax.plot(indices, values, color="blue", label="alphaBTC") | |
| ax.axhline(0, color="black", linewidth=1) | |
| ax.set_title("Alpha vs BTC", fontsize=14) | |
| ax.set_xlabel("Index") | |
| ax.set_ylabel("Alpha") | |
| ax.grid(True, linestyle="--", alpha=0.5) | |
| ax.legend() | |
| plt.tight_layout() | |
| if DEBUG: | |
| print("[DEBUG] Chart built successfully ✅") | |
| return fig | |
| except Exception as e: | |
| print(f"[ERROR] Exception while building chart: {e}") | |
| return None | |