Upload 8 files
Browse filesFiles changed (8)
- __pycache__/data_engine.cpython-314.pycAdded
- __pycache__/model_engine.cpython-314.pycAdded
- __pycache__/news_crawler.cpython-314.pycAdded
- app.pyAdded+281
- data_engine.pyAdded+96
- model_engine.pyAdded+38
- news_crawler.pyAdded+43
- requirements.txtAdded+10
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281import streamlit as st
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
import os
from datetime import datetime
from streamlit_autorefresh import st_autorefresh
# Official Hugging Face Spaces recommended fix
import warnings
warnings.filterwarnings("ignore", message="missing ScriptRunContext")
# 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)
# Fix: Only initialize autorefresh after script context is ready
import streamlit.runtime.scriptrunner
if streamlit.runtime.scriptrunner.get_script_run_ctx() is not None:
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")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import yfinance as yf
import pandas as pd
import numpy as np
def fetch_data(symbol, period='2y', interval='1d'):
"""
Fetch historical data for a given symbol.
Symbols: BTC-USD, ETH-USD, GC=F (Gold), CL=F (Oil), SI=F (Silver)
"""
ticker = yf.Ticker(symbol)
df = ticker.history(period=period, interval=interval)
return df
def add_indicators(df):
"""
Add technical indicators manually to avoid dependency issues with pandas_ta on Python 3.14.
"""
# EMA for trend
df['EMA_20'] = df['Close'].ewm(span=20, adjust=False).mean()
df['EMA_50'] = df['Close'].ewm(span=50, adjust=False).mean()
# RSI for momentum
delta = df['Close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
# Handle division by zero safely
rs = gain / loss.replace(0, np.finfo(float).eps)
df['RSI'] = 100 - (100 / (1 + rs))
# MACD
exp1 = df['Close'].ewm(span=12, adjust=False).mean()
exp2 = df['Close'].ewm(span=26, adjust=False).mean()
df['MACD'] = exp1 - exp2
df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
# Bollinger Bands
df['BB_Mid'] = df['Close'].rolling(window=20).mean()
df['BB_Std'] = df['Close'].rolling(window=20).std()
df['BB_Upper'] = df['BB_Mid'] + (df['BB_Std'] * 2)
df['BB_Lower'] = df['BB_Mid'] - (df['BB_Std'] * 2)
# ATR for volatility
high_low = df['High'] - df['Low']
high_close = np.abs(df['High'] - df['Close'].shift())
low_close = np.abs(df['Low'] - df['Close'].shift())
ranges = pd.concat([high_low, high_close, low_close], axis=1)
true_range = np.max(ranges, axis=1)
df['ATR'] = true_range.rolling(window=14).mean()
# Simple Candlestick Patterns
# Hammer: Small body, long lower shadow, little/no upper shadow
body = (df['Close'] - df['Open']).abs()
range_ = df['High'] - df['Low']
# Hammer definition: lower shadow > 2 * body, upper shadow < body, body in upper 1/3 of range
df['CDL_Hammer'] = (range_ > 3 * body) & \
((df[['Open', 'Close']].min(axis=1) - df['Low']) > 2 * body) & \
((df['High'] - df[['Open', 'Close']].max(axis=1)) < body)
# Engulfing: Current body completely covers previous body with opposite direction
prev_open = df['Open'].shift(1)
prev_close = df['Close'].shift(1)
# Bullish Engulfing
bull_eng = (df['Close'] > df['Open']) & (prev_close < prev_open) & \
(df['Close'] > prev_open) & (df['Open'] < prev_close)
# Bearish Engulfing
bear_eng = (df['Close'] < df['Open']) & (prev_close > prev_open) & \
(df['Close'] < prev_open) & (df['Open'] > prev_close)
df['CDL_Bull_Engulfing'] = bull_eng
df['CDL_Bear_Engulfing'] = bear_eng
df.dropna(inplace=True)
return df
def prepare_ml_data(df, window_size=10):
"""
Prepare sequences for the model.
"""
# Select numeric features only
features = ['Open', 'High', 'Low', 'Close', 'Volume', 'EMA_20', 'EMA_50', 'RSI', 'MACD', 'ATR']
data = df[features].values
# Target: Close price of the next day > current Close price
target = (df['Close'].shift(-1) > df['Close']).astype(int).values
X = []
y = []
for i in range(window_size, len(data) - 1):
X.append(data[i-window_size:i])
y.append(target[i])
# Also return the latest window for prediction (we don't have target for this one)
latest_window = data[len(data)-window_size:]
return np.array(X), np.array(y), latest_window1234567891011121314151617181920212223242526272829303132333435363738import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
class TradingModel:
def __init__(self):
self.scaler = StandardScaler()
self.model = LogisticRegression(random_state=42, max_iter=1000)
def train(self, X_train, y_train):
# Flatten 3D sequences into 2D for scikit-learn
n_samples, window_size, n_features = X_train.shape
X_flat = X_train.reshape(n_samples, window_size * n_features)
# Scale features
X_scaled = self.scaler.fit_transform(X_flat)
# Train model
self.model.fit(X_scaled, y_train)
def predict(self, X):
# Flatten and scale
n_samples, window_size, n_features = X.shape
X_flat = X.reshape(n_samples, window_size * n_features)
X_scaled = self.scaler.transform(X_flat)
# Return probability of positive class
return self.model.predict_proba(X_scaled)[:, 1]
def train_and_get_prediction(X_train, y_train, X_latest):
"""
Utility function to quickly train on historical data and predict next movement.
"""
tm = TradingModel()
tm.train(X_train, y_train)
pred = tm.predict(X_latest)
return pred[0]12345678910111213141516171819202122232425262728293031323334353637383940414243import requests
from bs4 import BeautifulSoup
def fetch_market_news(asset_name):
"""
Crawls news for the specific asset to provide context.
Using a simple crawler for demonstration purposes.
In a production bot, one would use specialized APIs like CryptoPanic or NewsAPI.
"""
search_query = asset_name.replace(" ", "+")
url = f"https://www.google.com/search?q={search_query}+market+news&tbm=nws"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
news_items = []
# Google news results usually have h3 tags for titles
for item in soup.find_all('div', {'class': 'SoN15'}): # Update based on current Google News structure or use an API
title = item.find('div', {'role': 'heading'}).text if item.find('div', {'role': 'heading'}) else "No Title"
snippet = item.find('div', {'class': 'GI74ad'}).text if item.find('div', {'class': 'GI74ad'}) else ""
news_items.append({"title": title, "snippet": snippet})
if not news_items:
# Fallback to a simpler selector if Google changes classes
for g in soup.find_all('div', {'class': 'g'}):
title = g.find('h3').text if g.find('h3') else "No Title"
news_items.append({"title": title, "snippet": ""})
return news_items[:5] # Return top 5 news items
except Exception as e:
print(f"Error fetching news for {asset_name}: {e}")
return []
if __name__ == "__main__":
print("Testing News Crawler for BTC...")
news = fetch_market_news("Bitcoin")
for n in news:
print(f"- {n['title']}")12345678910streamlit>=1.35.0
pandas>=2.0.0
numpy>=1.24.0
plotly>=5.15.0
yfinance>=0.2.30
beautifulsoup4>=4.12.0
requests>=2.31.0
scikit-learn>=1.3.0
streamlit-autorefresh>=1.0.0
extra-streamlit-components>=0.1.0__pycache__/data_engine.cpython-314.pycAdded
__pycache__/model_engine.cpython-314.pycAdded
__pycache__/news_crawler.cpython-314.pycAdded
app.pyAdded+281
data_engine.pyAdded+96
model_engine.pyAdded+38
news_crawler.pyAdded+43
requirements.txtAdded+10