File size: 2,119 Bytes
b2d5b74
 
 
 
 
 
 
 
 
 
 
2fcf62a
b2d5b74
 
 
 
 
2fcf62a
b2d5b74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
🇬🇧 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