Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319# ULTIMATE HUGGING FACE SPACES FIX
# This will 100% stop all ScriptRunContext warnings
import os
import sys
import io
# -----------------------------------------------------------------------------
# FIRST: MUTE ALL OUTPUT DURING IMPORTS - THIS IS THE ONLY THING THAT WORKS
# -----------------------------------------------------------------------------
# Save original stdout/stderr
old_stdout = sys.stdout
old_stderr = sys.stderr
# Redirect everything to null
null = io.StringIO()
sys.stdout = null
sys.stderr = null
# Now import every problematic module while output is completely muted
try:
import warnings
warnings.filterwarnings("ignore")
import logging
logging.disable(logging.CRITICAL)
os.environ['STREAMLIT_LOG_LEVEL'] = 'CRITICAL'
os.environ['STREAMLIT_BROWSER_GATHER_USAGE_STATS'] = 'false'
# Now import Streamlit ONE TIME while output is completely muted
import streamlit
except:
pass
# Restore normal output
sys.stdout = old_stdout
sys.stderr = old_stderr
# Now import everything else
import pandas as pd
import plotly.graph_objects as go
from data_engine import fetch_data, add_indicators, prepare_ml_data
from model_engine import train_and_get_prediction
from news_crawler import fetch_market_news
import numpy as np
import time
from datetime import datetime
def main():
# ONLY import Streamlit inside main function when actually running
import streamlit as st
from streamlit_autorefresh import st_autorefresh
# Page Configuration
st.set_page_config(page_title="AI Trading Signal Bot", layout="wide")
# --------------------------
# INITIALIZE SESSION STATE
# --------------------------
if 'last_signal' not in st.session_state:
st.session_state.last_signal = None
if 'signal_history' not in st.session_state:
st.session_state.signal_history = []
if 'auto_mode' not in st.session_state:
st.session_state.auto_mode = False
if 'refresh_interval' not in st.session_state:
st.session_state.refresh_interval = 60000
if 'notifications_enabled' not in st.session_state:
st.session_state.notifications_enabled = False
if 'sound_enabled' not in st.session_state:
st.session_state.sound_enabled = True
# --------------------------
# SIDEBAR
# --------------------------
st.sidebar.header("βοΈ Controls")
# Asset Selection
st.sidebar.header("Market Selection")
asset_map = {
"Bitcoin (BTC)": "BTC-USD",
"Ethereum (ETH)": "ETH-USD",
"Gold": "GC=F",
"Silver": "SI=F",
"Crude Oil": "CL=F"
}
selected_asset_name = st.sidebar.selectbox("Choose Asset", list(asset_map.keys()))
selected_symbol = asset_map[selected_asset_name]
# Timeframe selection (including new 1min)
timeframe = st.sidebar.selectbox("Timeframe", ["1m", "5m", "15m", "1h", "1d"], index=3)
# Set appropriate period based on timeframe
period_map = {
"1m": "7d",
"5m": "60d",
"15m": "60d",
"1h": "1mo",
"1d": "2y"
}
period = period_map[timeframe]
st.sidebar.markdown("---")
# Auto Pilot Mode
st.sidebar.header("π€ Auto Pilot Mode")
auto_mode = st.sidebar.toggle("Enable Auto Refresh", value=st.session_state.auto_mode)
st.session_state.auto_mode = auto_mode
if auto_mode:
refresh_options = {
"1 Minute": 60000,
"5 Minutes": 300000,
"15 Minutes": 900000,
"30 Minutes": 1800000
}
refresh_label = st.sidebar.selectbox("Refresh Interval", list(refresh_options.keys()), index=1)
st.session_state.refresh_interval = refresh_options[refresh_label]
st.session_state.notifications_enabled = st.sidebar.toggle("π Push Notifications", value=st.session_state.notifications_enabled)
st.session_state.sound_enabled = st.sidebar.toggle("π Sound Alert", value=st.session_state.sound_enabled)
st_autorefresh(interval=st.session_state.refresh_interval, key="autorefresh")
st.sidebar.success("β
Auto Mode Active")
else:
st.sidebar.info("βΈ Auto Mode Paused")
st.sidebar.markdown("---")
# Manual Generate Button
generate_clicked = st.sidebar.button("π Generate Signal Now", type="primary", use_container_width=True)
st.sidebar.markdown("---")
st.sidebar.write("Asset Coverage: BTC, ETH, Gold, Oil, Silver")
st.sidebar.caption("β οΈ This is for educational purposes only. Not financial advice.")
# --------------------------
# MAIN APPLICATION
# --------------------------
st.title("π AI Trading Signal Bot")
if auto_mode:
st.info(f"π€ Auto Pilot is ACTIVE. Auto refreshing every {refresh_label}. Last update: {datetime.now().strftime('%H:%M:%S')}")
st.markdown("""
This bot uses **Machine Learning** and **Technical Indicators** to predict market signals.
It analyzes candlestick patterns and crawls recent news for context.
""")
if generate_clicked or auto_mode:
with st.spinner(f"Analyzing {selected_asset_name}..."):
# 1. Fetch Data
df = fetch_data(selected_symbol, period=period, interval=timeframe)
if df.empty:
st.error("Could not fetch data. Please try again later.")
else:
# 2. Add Indicators
df_with_ind = add_indicators(df.copy())
# 3. Prepare ML Data and Predict
X, y, latest_window = prepare_ml_data(df_with_ind)
if len(X) == 0:
st.warning("Not enough data to generate a signal for this timeframe.")
else:
# Reshape latest window for model input
latest_window = latest_window.reshape(1, latest_window.shape[0], latest_window.shape[1])
prediction_prob = train_and_get_prediction(X, y, latest_window)
# 4. News Crawling
news_items = fetch_market_news(selected_asset_name)
# --- UI DISPLAY ---
col1, col2 = st.columns([2, 1])
with col1:
st.subheader(f"{selected_asset_name} Price Chart & Signal")
# Signal logic
if prediction_prob > 0.55:
signal = "BUY"
color = "green"
elif prediction_prob < 0.45:
signal = "SELL"
color = "red"
else:
signal = "HOLD"
color = "gray"
confidence = abs(prediction_prob - 0.5) * 200 # Normalized to 0-100%
st.markdown(f"""
<div style="padding:20px; border-radius:10px; background-color:#1e1e1e; border-left: 10px solid {color}; color: white;">
<h2 style="color:{color}; margin:0;">SIGNAL: {signal}</h2>
<p style="margin:0;">AI Model Confidence: {confidence:.2f}%</p>
<p style="margin:0; font-size:12px; opacity:0.7;">Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
</div>
""", unsafe_allow_html=True)
# Check for signal change
if st.session_state.last_signal is not None and st.session_state.last_signal != signal:
# Signal changed - trigger notification
if st.session_state.notifications_enabled:
st.toast(f"π SIGNAL CHANGE: {signal} for {selected_asset_name}", icon="π¨")
# Browser notification script
st.components.v1.html(f"""
<script>
if (Notification.permission === "granted") {{
new Notification("AI Trading Bot", {{
body: "SIGNAL {signal} for {selected_asset_name} - Confidence: {confidence:.2f}%",
icon: "https://cdn-icons-png.flaticon.com/512/1035/1035688.png"
}});
{f"new Audio('https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3').play();" if st.session_state.sound_enabled else ""}
}}
</script>
""", height=0)
# Save current signal
st.session_state.last_signal = signal
# Add to history
history_entry = {
"time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"asset": selected_asset_name,
"signal": signal,
"confidence": f"{confidence:.2f}%"
}
st.session_state.signal_history.insert(0, history_entry)
if len(st.session_state.signal_history) > 20:
st.session_state.signal_history.pop()
# Plotly Chart
fig = go.Figure(data=[go.Candlestick(x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name="Candlestick")])
fig.add_trace(go.Scatter(x=df_with_ind.index, y=df_with_ind['EMA_20'], name="EMA 20", line=dict(color='orange', width=1)))
fig.add_trace(go.Scatter(x=df_with_ind.index, y=df_with_ind['EMA_50'], name="EMA 50", line=dict(color='blue', width=1)))
fig.update_layout(xaxis_rangeslider_visible=False, template="plotly_dark", height=500)
st.plotly_chart(fig, use_container_width=True)
st.write("### Technical Indicators (Latest)")
st.dataframe(df_with_ind[['Close', 'EMA_20', 'EMA_50', 'RSI', 'MACD', 'ATR']].tail(5), use_container_width=True)
with col2:
# Notification permission request
if st.session_state.notifications_enabled:
st.components.v1.html("""
<script>
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
</script>
""", height=0)
st.subheader("π° Market Context")
if news_items:
for item in news_items[:5]:
st.markdown(f"**{item['title']}**")
if item['snippet']:
st.caption(item['snippet'])
st.divider()
else:
st.write("No recent news found.")
st.subheader("π―οΈ Candlestick Strategy")
# Find recent patterns
pattern_cols = [col for col in df_with_ind.columns if col.startswith('CDL')]
recent_patterns = df_with_ind[pattern_cols].tail(1).iloc[0]
detected = recent_patterns[recent_patterns == True]
if not detected.empty:
st.write("Current Candle Patterns:")
for pat in detected.index:
name = pat.replace('CDL_', '').replace('_', ' ')
st.success(f"β
Detected: {name}")
else:
st.info("βΉοΈ No strong candlestick patterns in the current candle.")
st.subheader("π Signal History")
if st.session_state.signal_history:
history_df = pd.DataFrame(st.session_state.signal_history)
st.dataframe(history_df, use_container_width=True, hide_index=True)
else:
st.write("No signal history yet.")
else:
st.info("π Select an asset from the sidebar and click 'Generate Signal Now' or enable Auto Pilot Mode to start.")
# First run welcome
st.markdown("---")
st.subheader("π Features:")
colf1, colf2, colf3 = st.columns(3)
with colf1:
st.markdown("β
Real live market data")
st.markdown("β
1 minute timeframe support")
st.markdown("β
ML trained predictions")
with colf2:
st.markdown("β
Auto Pilot auto refresh mode")
st.markdown("β
Browser push notifications")
st.markdown("β
Sound alerts")
with colf3:
st.markdown("β
Public access without login")
st.markdown("β
Signal change detection")
st.markdown("β
Signal history log")
# Hugging Face Spaces automatically executes this correctly
if __name__ == "__main__":
main()app.pyDeleted-319