File size: 3,373 Bytes
e2bee6b
 
 
 
 
 
 
 
 
 
 
b9f2b41
e2bee6b
 
 
c1893a4
e2bee6b
 
 
c1893a4
e2bee6b
c1893a4
 
e2bee6b
 
 
 
 
 
 
 
 
 
 
 
 
c1893a4
e2bee6b
 
 
 
 
 
c1893a4
 
 
 
e2bee6b
c1893a4
 
 
 
 
e2bee6b
 
 
c1893a4
 
 
 
 
 
e2bee6b
 
 
c1893a4
e2bee6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import os
import io
import json
import base64
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv

load_dotenv()

from llm_proxy import get_llm_client

class LLMVisionEngine:
    def __init__(self):
        self.proxy = get_llm_client()

    def analyze_chart(self, ticker: str, df: pd.DataFrame) -> dict:
        """
        Generates a chart image and asks the LLM to interpret the patterns.
        """
        if self.proxy.mode == "none":
            return {"error": "LLM Proxy unavailable"}

        # 1. Generate the Chart
        img_bytes = self._generate_chart_bytes(ticker, df)
        
        # 2. Prepare Prompt
        prompt = f"""
        Analyze this stock chart for {ticker}. 
        Identify key technical patterns (e.g., support/resistance, breakouts, trendlines).
        Predict the likely direction for the next 5-10 bars.
        
        Respond ONLY with this JSON format:
        {{
            "direction": "bullish|bearish|neutral",
            "score": <float -0.99 to 0.99>,
            "reasoning": "<one sentence analysis of visual patterns>",
            "patterns": ["pattern1", "pattern2"]
        }}
        """

        try:
            # 3. Send to Proxy
            text = self.proxy.generate_content(prompt, image_bytes=img_bytes)
            text = text.strip()

            if "```" in text:
                parts = text.split("```")
                if len(parts) >= 2:
                    text = parts[1]
                    if text.startswith("json"):
                        text = text[4:]
                text = text.strip()
                
            prediction = json.loads(text)
            prediction["source"] = f"llm_proxy_vision/{self.proxy.mode}"
            
            # Ensure score is rounded and clamped
            raw_score = float(prediction.get("score", 0.0))
            prediction["score"] = round(max(-0.99, min(0.99, raw_score)), 3)
            
            return prediction

        except Exception as e:
            print(f"[Vision] Engine error: {e}")
            return {"error": str(e)}

    def _generate_chart_bytes(self, ticker: str, df: pd.DataFrame) -> bytes:
        """Helper to create a matplotlib chart and return raw bytes."""
        plt.figure(figsize=(10, 6))
        
        # Plot Close price
        plt.plot(df.index, df['Close'], label='Close', color='#2196F3', linewidth=2)
        
        # Add a few key indicators if present
        if 'SMA_20' in df.columns:
            plt.plot(df.index, df['SMA_20'], label='SMA 20', color='#FF9800', linestyle='--', alpha=0.7)
        if 'SMA_50' in df.columns:
            plt.plot(df.index, df['SMA_50'], label='SMA 50', color='#E91E63', linestyle='--', alpha=0.7)
            
        plt.title(f"{ticker} - Market Analysis Graph", color='white', fontsize=14)
        plt.grid(True, alpha=0.2)
        plt.legend()
        
        # Style for Dark Mode (matching UI)
        plt.gca().set_facecolor('#0f172a')
        plt.gcf().set_facecolor('#0f172a')
        plt.tick_params(colors='white')
        for spine in plt.gca().spines.values():
            spine.set_color('#334155')

        # Save to buffer
        buf = io.BytesIO()
        plt.savefig(buf, format='png', bbox_inches='tight', facecolor='#0f172a')
        plt.close()
        return buf.getvalue()