MrBro123 commited on
Commit
1af940d
·
verified ·
1 Parent(s): 70cdf92

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -319
app.py DELETED
@@ -1,319 +0,0 @@
1
- # ULTIMATE HUGGING FACE SPACES FIX
2
- # This will 100% stop all ScriptRunContext warnings
3
-
4
- import os
5
- import sys
6
- import io
7
-
8
- # -----------------------------------------------------------------------------
9
- # FIRST: MUTE ALL OUTPUT DURING IMPORTS - THIS IS THE ONLY THING THAT WORKS
10
- # -----------------------------------------------------------------------------
11
- # Save original stdout/stderr
12
- old_stdout = sys.stdout
13
- old_stderr = sys.stderr
14
-
15
- # Redirect everything to null
16
- null = io.StringIO()
17
- sys.stdout = null
18
- sys.stderr = null
19
-
20
- # Now import every problematic module while output is completely muted
21
- try:
22
- import warnings
23
- warnings.filterwarnings("ignore")
24
- import logging
25
- logging.disable(logging.CRITICAL)
26
-
27
- os.environ['STREAMLIT_LOG_LEVEL'] = 'CRITICAL'
28
- os.environ['STREAMLIT_BROWSER_GATHER_USAGE_STATS'] = 'false'
29
-
30
- # Now import Streamlit ONE TIME while output is completely muted
31
- import streamlit
32
- except:
33
- pass
34
-
35
- # Restore normal output
36
- sys.stdout = old_stdout
37
- sys.stderr = old_stderr
38
-
39
- # Now import everything else
40
- import pandas as pd
41
- import plotly.graph_objects as go
42
- from data_engine import fetch_data, add_indicators, prepare_ml_data
43
- from model_engine import train_and_get_prediction
44
- from news_crawler import fetch_market_news
45
- import numpy as np
46
- import time
47
- from datetime import datetime
48
-
49
-
50
- def main():
51
- # ONLY import Streamlit inside main function when actually running
52
- import streamlit as st
53
- from streamlit_autorefresh import st_autorefresh
54
-
55
- # Page Configuration
56
- st.set_page_config(page_title="AI Trading Signal Bot", layout="wide")
57
-
58
- # --------------------------
59
- # INITIALIZE SESSION STATE
60
- # --------------------------
61
- if 'last_signal' not in st.session_state:
62
- st.session_state.last_signal = None
63
- if 'signal_history' not in st.session_state:
64
- st.session_state.signal_history = []
65
- if 'auto_mode' not in st.session_state:
66
- st.session_state.auto_mode = False
67
- if 'refresh_interval' not in st.session_state:
68
- st.session_state.refresh_interval = 60000
69
- if 'notifications_enabled' not in st.session_state:
70
- st.session_state.notifications_enabled = False
71
- if 'sound_enabled' not in st.session_state:
72
- st.session_state.sound_enabled = True
73
-
74
- # --------------------------
75
- # SIDEBAR
76
- # --------------------------
77
- st.sidebar.header("⚙️ Controls")
78
-
79
- # Asset Selection
80
- st.sidebar.header("Market Selection")
81
- asset_map = {
82
- "Bitcoin (BTC)": "BTC-USD",
83
- "Ethereum (ETH)": "ETH-USD",
84
- "Gold": "GC=F",
85
- "Silver": "SI=F",
86
- "Crude Oil": "CL=F"
87
- }
88
-
89
- selected_asset_name = st.sidebar.selectbox("Choose Asset", list(asset_map.keys()))
90
- selected_symbol = asset_map[selected_asset_name]
91
-
92
- # Timeframe selection (including new 1min)
93
- timeframe = st.sidebar.selectbox("Timeframe", ["1m", "5m", "15m", "1h", "1d"], index=3)
94
-
95
- # Set appropriate period based on timeframe
96
- period_map = {
97
- "1m": "7d",
98
- "5m": "60d",
99
- "15m": "60d",
100
- "1h": "1mo",
101
- "1d": "2y"
102
- }
103
- period = period_map[timeframe]
104
-
105
- st.sidebar.markdown("---")
106
-
107
- # Auto Pilot Mode
108
- st.sidebar.header("🤖 Auto Pilot Mode")
109
- auto_mode = st.sidebar.toggle("Enable Auto Refresh", value=st.session_state.auto_mode)
110
- st.session_state.auto_mode = auto_mode
111
-
112
- if auto_mode:
113
- refresh_options = {
114
- "1 Minute": 60000,
115
- "5 Minutes": 300000,
116
- "15 Minutes": 900000,
117
- "30 Minutes": 1800000
118
- }
119
- refresh_label = st.sidebar.selectbox("Refresh Interval", list(refresh_options.keys()), index=1)
120
- st.session_state.refresh_interval = refresh_options[refresh_label]
121
-
122
- st.session_state.notifications_enabled = st.sidebar.toggle("🔔 Push Notifications", value=st.session_state.notifications_enabled)
123
- st.session_state.sound_enabled = st.sidebar.toggle("🔊 Sound Alert", value=st.session_state.sound_enabled)
124
-
125
- st_autorefresh(interval=st.session_state.refresh_interval, key="autorefresh")
126
-
127
- st.sidebar.success("✅ Auto Mode Active")
128
- else:
129
- st.sidebar.info("⏸ Auto Mode Paused")
130
-
131
- st.sidebar.markdown("---")
132
-
133
- # Manual Generate Button
134
- generate_clicked = st.sidebar.button("📊 Generate Signal Now", type="primary", use_container_width=True)
135
-
136
- st.sidebar.markdown("---")
137
- st.sidebar.write("Asset Coverage: BTC, ETH, Gold, Oil, Silver")
138
- st.sidebar.caption("⚠️ This is for educational purposes only. Not financial advice.")
139
-
140
- # --------------------------
141
- # MAIN APPLICATION
142
- # --------------------------
143
- st.title("🚀 AI Trading Signal Bot")
144
-
145
- if auto_mode:
146
- st.info(f"🤖 Auto Pilot is ACTIVE. Auto refreshing every {refresh_label}. Last update: {datetime.now().strftime('%H:%M:%S')}")
147
-
148
- st.markdown("""
149
- This bot uses **Machine Learning** and **Technical Indicators** to predict market signals.
150
- It analyzes candlestick patterns and crawls recent news for context.
151
- """)
152
-
153
- if generate_clicked or auto_mode:
154
- with st.spinner(f"Analyzing {selected_asset_name}..."):
155
- # 1. Fetch Data
156
- df = fetch_data(selected_symbol, period=period, interval=timeframe)
157
-
158
- if df.empty:
159
- st.error("Could not fetch data. Please try again later.")
160
- else:
161
- # 2. Add Indicators
162
- df_with_ind = add_indicators(df.copy())
163
-
164
- # 3. Prepare ML Data and Predict
165
- X, y, latest_window = prepare_ml_data(df_with_ind)
166
-
167
- if len(X) == 0:
168
- st.warning("Not enough data to generate a signal for this timeframe.")
169
- else:
170
- # Reshape latest window for model input
171
- latest_window = latest_window.reshape(1, latest_window.shape[0], latest_window.shape[1])
172
- prediction_prob = train_and_get_prediction(X, y, latest_window)
173
-
174
- # 4. News Crawling
175
- news_items = fetch_market_news(selected_asset_name)
176
-
177
- # --- UI DISPLAY ---
178
- col1, col2 = st.columns([2, 1])
179
-
180
- with col1:
181
- st.subheader(f"{selected_asset_name} Price Chart & Signal")
182
-
183
- # Signal logic
184
- if prediction_prob > 0.55:
185
- signal = "BUY"
186
- color = "green"
187
- elif prediction_prob < 0.45:
188
- signal = "SELL"
189
- color = "red"
190
- else:
191
- signal = "HOLD"
192
- color = "gray"
193
-
194
- confidence = abs(prediction_prob - 0.5) * 200 # Normalized to 0-100%
195
-
196
- st.markdown(f"""
197
- <div style="padding:20px; border-radius:10px; background-color:#1e1e1e; border-left: 10px solid {color}; color: white;">
198
- <h2 style="color:{color}; margin:0;">SIGNAL: {signal}</h2>
199
- <p style="margin:0;">AI Model Confidence: {confidence:.2f}%</p>
200
- <p style="margin:0; font-size:12px; opacity:0.7;">Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
201
- </div>
202
- """, unsafe_allow_html=True)
203
-
204
- # Check for signal change
205
- if st.session_state.last_signal is not None and st.session_state.last_signal != signal:
206
- # Signal changed - trigger notification
207
- if st.session_state.notifications_enabled:
208
- st.toast(f"🔔 SIGNAL CHANGE: {signal} for {selected_asset_name}", icon="🚨")
209
-
210
- # Browser notification script
211
- st.components.v1.html(f"""
212
- <script>
213
- if (Notification.permission === "granted") {{
214
- new Notification("AI Trading Bot", {{
215
- body: "SIGNAL {signal} for {selected_asset_name} - Confidence: {confidence:.2f}%",
216
- icon: "https://cdn-icons-png.flaticon.com/512/1035/1035688.png"
217
- }});
218
- {f"new Audio('https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3').play();" if st.session_state.sound_enabled else ""}
219
- }}
220
- </script>
221
- """, height=0)
222
-
223
- # Save current signal
224
- st.session_state.last_signal = signal
225
-
226
- # Add to history
227
- history_entry = {
228
- "time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
229
- "asset": selected_asset_name,
230
- "signal": signal,
231
- "confidence": f"{confidence:.2f}%"
232
- }
233
- st.session_state.signal_history.insert(0, history_entry)
234
- if len(st.session_state.signal_history) > 20:
235
- st.session_state.signal_history.pop()
236
-
237
- # Plotly Chart
238
- fig = go.Figure(data=[go.Candlestick(x=df.index,
239
- open=df['Open'],
240
- high=df['High'],
241
- low=df['Low'],
242
- close=df['Close'],
243
- name="Candlestick")])
244
-
245
- 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)))
246
- 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)))
247
-
248
- fig.update_layout(xaxis_rangeslider_visible=False, template="plotly_dark", height=500)
249
- st.plotly_chart(fig, use_container_width=True)
250
-
251
- st.write("### Technical Indicators (Latest)")
252
- st.dataframe(df_with_ind[['Close', 'EMA_20', 'EMA_50', 'RSI', 'MACD', 'ATR']].tail(5), use_container_width=True)
253
-
254
- with col2:
255
- # Notification permission request
256
- if st.session_state.notifications_enabled:
257
- st.components.v1.html("""
258
- <script>
259
- if (Notification.permission !== "granted") {
260
- Notification.requestPermission();
261
- }
262
- </script>
263
- """, height=0)
264
-
265
- st.subheader("📰 Market Context")
266
- if news_items:
267
- for item in news_items[:5]:
268
- st.markdown(f"**{item['title']}**")
269
- if item['snippet']:
270
- st.caption(item['snippet'])
271
- st.divider()
272
- else:
273
- st.write("No recent news found.")
274
-
275
- st.subheader("🕯️ Candlestick Strategy")
276
- # Find recent patterns
277
- pattern_cols = [col for col in df_with_ind.columns if col.startswith('CDL')]
278
- recent_patterns = df_with_ind[pattern_cols].tail(1).iloc[0]
279
- detected = recent_patterns[recent_patterns == True]
280
-
281
- if not detected.empty:
282
- st.write("Current Candle Patterns:")
283
- for pat in detected.index:
284
- name = pat.replace('CDL_', '').replace('_', ' ')
285
- st.success(f"✅ Detected: {name}")
286
- else:
287
- st.info("ℹ️ No strong candlestick patterns in the current candle.")
288
-
289
- st.subheader("📜 Signal History")
290
- if st.session_state.signal_history:
291
- history_df = pd.DataFrame(st.session_state.signal_history)
292
- st.dataframe(history_df, use_container_width=True, hide_index=True)
293
- else:
294
- st.write("No signal history yet.")
295
-
296
- else:
297
- st.info("👆 Select an asset from the sidebar and click 'Generate Signal Now' or enable Auto Pilot Mode to start.")
298
-
299
- # First run welcome
300
- st.markdown("---")
301
- st.subheader("📌 Features:")
302
- colf1, colf2, colf3 = st.columns(3)
303
- with colf1:
304
- st.markdown("✅ Real live market data")
305
- st.markdown("✅ 1 minute timeframe support")
306
- st.markdown("✅ ML trained predictions")
307
- with colf2:
308
- st.markdown("✅ Auto Pilot auto refresh mode")
309
- st.markdown("✅ Browser push notifications")
310
- st.markdown("✅ Sound alerts")
311
- with colf3:
312
- st.markdown("✅ Public access without login")
313
- st.markdown("✅ Signal change detection")
314
- st.markdown("✅ Signal history log")
315
-
316
-
317
- # Hugging Face Spaces automatically executes this correctly
318
- if __name__ == "__main__":
319
- main()