tradingAI / app.py
yougandar's picture
Update app.py
0dc6c6b verified
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()