File size: 4,322 Bytes
b85ae4e
bcf884f
 
812b49a
95a6480
007107c
b53d4ce
1fcebf9
 
95a6480
 
 
 
 
 
 
313dc3a
95a6480
b53d4ce
1f52945
b53d4ce
812b49a
bcf884f
b53d4ce
 
007107c
1fcebf9
 
 
95a6480
 
 
 
 
 
bcf884f
 
 
 
 
 
 
 
 
95a6480
 
007107c
 
 
 
0dc6c6b
007107c
bcf884f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
007107c
bcf884f
 
 
007107c
bcf884f
 
007107c
bcf884f
 
 
 
 
 
 
 
007107c
bcf884f
 
 
 
007107c
 
bcf884f
 
 
 
 
 
 
 
 
 
 
 
95a6480
bcf884f
 
 
 
 
 
 
 
 
b53d4ce
313dc3a
bcf884f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import gradio as gr
from datetime import datetime

from polygon_loader import fetch_ohlcv

# Import AI agents
from trend_agent import TrendWatcherAgent
from volume_agent import VolumeSurgeAgent
from crossover_agent import CrossoverAgent
from rsi_agent import RSIAlertAgent
from supertrend_agent import SupertrendAgent
from retracement_agent import RetracementAgent
from rainbow_agent import RainbowAgent
from sentiment_agent import SentimentAgent
from adaptive_agent import AdaptiveAgent


def predict_all(symbol):
    symbol = symbol.strip().upper()
    df = fetch_ohlcv(symbol)

    if df is None or df.empty:
        return [], [], "❌ No data available. Try again or check the symbol."

    try:
        # Run agents
        trend_agent = TrendWatcherAgent()
        vol_agent = VolumeSurgeAgent()
        cross_agent = CrossoverAgent()
        rsi_agent = RSIAlertAgent()
        super_agent = SupertrendAgent()
        retrace_agent = RetracementAgent()
        rainbow_agent = RainbowAgent()
        sentiment_agent = SentimentAgent()
        adaptive_agent = AdaptiveAgent()

        trend = trend_agent.run(df)
        vol = vol_agent.run(df)
        cross = cross_agent.run(df)
        rsi = rsi_agent.run(df)
        st = super_agent.run(df)
        retrace = retrace_agent.run(df)
        rainbow = rainbow_agent.run(df)
        sentiment = sentiment_agent.run(symbol)
        adaptive = adaptive_agent.run(df)

        # Prices and rounding
        entry_price = float(round(df["Close"].iloc[-1], 2))
        sl = float(round(entry_price * 0.985, 2))
        target = float(round(entry_price * 1.02, 2))
        now_time = datetime.now().strftime("%Y-%m-%d %I:%M%p").lower()
        confidence_str = f"{float(trend['confidence'])}%"

        # Explanation map
        Signal_Explanation__c = {
            "Uptrend": "EMA50↑, RSI above 55, supported by volume",
            "Downtrend": "EMA50↓, RSI below 45, bearish confirmation",
            "Neutral": "Indicators are mixed or non-directional"
        }
        explanation = Signal_Explanation__c.get(trend["trend"], "No explanation available.")

        # Live signal dashboard
        signal_table = [[
            symbol,
            trend['trend'].replace("trend", ""),
            entry_price,
            sl,
            target,
            confidence_str,
            now_time
        ]]

        # Detail panel (markdown)
        signal_md = f"""
[Stock: {symbol}]  
**Trend:** {trend['trend']} | **Confidence:** {confidence_str}  
β†’ **Entry:** {entry_price} | **SL:** {sl} | 🎯 **Target:** {target}

**[Why This Signal?]**  
β†’ {explanation}  
β†’ Indicators: EMA50 {'↑' if cross['crossover'] == 'Bullish' else '↓' if cross['crossover'] == 'Bearish' else '-'}, RSI={rsi['rsi']}, Volume: {"Spike" if vol['volume_surge'] else "Normal"}  
β†’ Historical Similar Case: April 7, 5min TF
"""

        # Portfolio view
        portfolio_table = [[
            symbol,
            "Up" if trend['trend'] == "Uptrend" else "Down",
            "Neutral",
            trend["trend"],
            confidence_str,
            "Generated by AI Agents"
        ]]

        return signal_table, portfolio_table, signal_md

    except Exception as e:
        return [], [], f"❌ Agent Error: {str(e)}"


# Gradio UI
with gr.Blocks(title="πŸ“ˆ Intraday AI Signal Engine") as app:
    gr.Markdown("## 🧠 Intraday Trading Signal – Multi-Agent AI Engine")

    with gr.Row():
        symbol_input = gr.Textbox(label="Enter Stock Symbol (e.g., AAPL, MSFT, INFY)", placeholder="e.g., AAPL")
        scan_btn = gr.Button("πŸ” Run AI Agents")

    with gr.Column():
        signal_table = gr.Dataframe(
            headers=["Symbol", "Trend", "Entry", "SL", "Target", "Confidence", "Updated"],
            label="πŸ“Š Live Signal Dashboard",
            interactive=False
        )

        signal_md = gr.Markdown("ℹ️ Signal details will appear here...")

        portfolio_table = gr.Dataframe(
            headers=["Stock", "1H Trend", "4H Trend", "Daily Trend", "Confidence", "Comment"],
            label="🧠 Portfolio View (Multi-Timeframe)",
            interactive=False
        )

    scan_btn.click(
        fn=predict_all,
        inputs=[symbol_input],
        outputs=[signal_table, portfolio_table, signal_md]
    )

app.launch()