Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import yfinance as yf | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| from transformers import pipeline | |
| import torch | |
| from sklearn.preprocessing import MinMaxScaler | |
| class AdvancedTradingPredictionApp: | |
| def __init__(self): | |
| # Initialize key configurations | |
| self.trading_pairs = { | |
| 'Bitcoin': 'BTC-USD', | |
| 'Ethereum': 'ETH-USD', | |
| 'Binance Coin': 'BNB-USD', | |
| 'Cardano': 'ADA-USD', | |
| 'Solana': 'SOL-USD' | |
| } | |
| # Load pre-trained sentiment and forecasting models | |
| try: | |
| self.sentiment_model = pipeline("sentiment-analysis") | |
| self.forecasting_model = self.load_forecasting_model() | |
| except Exception as e: | |
| st.error(f"Model loading error: {e}") | |
| def load_forecasting_model(self): | |
| # Simulate a more advanced forecasting approach | |
| class SimpleForecaster: | |
| def __init__(self): | |
| self.scaler = MinMaxScaler() | |
| def predict(self, data, days_ahead=7): | |
| # Normalize data | |
| scaled_data = self.scaler.fit_transform(data.reshape(-1, 1)) | |
| # Simple prediction logic | |
| trend = np.polyfit(range(len(scaled_data)), scaled_data.flatten(), 1)[0] | |
| # Generate forecast | |
| last_value = scaled_data[-1] | |
| forecast = [last_value] | |
| for _ in range(days_ahead): | |
| next_val = forecast[-1] + trend | |
| forecast.append(next_val) | |
| # Inverse transform to get actual prices | |
| forecast = self.scaler.inverse_transform(np.array(forecast[1:]).reshape(-1, 1)) | |
| return forecast.flatten() | |
| return SimpleForecaster() | |
| def fetch_historical_data(self, symbol, period='1y'): | |
| """Fetch historical price data for a given symbol""" | |
| try: | |
| df = yf.download(symbol, period=period) | |
| return df | |
| except Exception as e: | |
| st.error(f"Data fetching error for {symbol}: {e}") | |
| return None | |
| def calculate_technical_indicators(self, df): | |
| """Calculate advanced technical indicators""" | |
| # RSI Calculation | |
| delta = df['Close'].diff() | |
| gain = (delta.where(delta > 0, 0)).rolling(window=14).mean() | |
| loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean() | |
| rs = gain / loss | |
| df['RSI'] = 100 - (100 / (1 + rs)) | |
| # Moving Averages | |
| df['SMA_50'] = df['Close'].rolling(window=50).mean() | |
| df['SMA_200'] = df['Close'].rolling(window=200).mean() | |
| # MACD | |
| exp1 = df['Close'].ewm(span=12, adjust=False).mean() | |
| exp2 = df['Close'].ewm(span=26, adjust=False).mean() | |
| df['MACD'] = exp1 - exp2 | |
| return df | |
| def sentiment_analysis(self, text): | |
| """Perform sentiment analysis on trading-related text""" | |
| try: | |
| return self.sentiment_model(text)[0] | |
| except Exception as e: | |
| st.error(f"Sentiment analysis error: {e}") | |
| return None | |
| def advanced_prediction(self, df): | |
| """Advanced price prediction with multiple techniques""" | |
| # Prepare data for prediction | |
| close_prices = df['Close'].values | |
| # Use forecasting model to predict next 7 days | |
| try: | |
| predictions = self.forecasting_model.predict(close_prices) | |
| return predictions | |
| except Exception as e: | |
| st.error(f"Prediction error: {e}") | |
| return None | |
| def main(): | |
| st.set_page_config(page_title="๐ Advanced Crypto Trading Predictor", layout="wide") | |
| st.title("๐ Advanced Cryptocurrency Trading Prediction Platform") | |
| # Initialize the trading prediction app | |
| app = AdvancedTradingPredictionApp() | |
| # Sidebar for asset and configuration | |
| st.sidebar.header("Trading Configuration") | |
| selected_crypto = st.sidebar.selectbox( | |
| "Select Cryptocurrency", | |
| list(app.trading_pairs.keys()), | |
| index=0 | |
| ) | |
| # Fetch historical data | |
| symbol = app.trading_pairs[selected_crypto] | |
| historical_data = app.fetch_historical_data(symbol) | |
| if historical_data is not None: | |
| # Calculate technical indicators | |
| data_with_indicators = app.calculate_technical_indicators(historical_data) | |
| # Prediction Section | |
| st.subheader(f"๐ฎ {selected_crypto} Price Prediction") | |
| # Make predictions | |
| predictions = app.advanced_prediction(data_with_indicators) | |
| if predictions is not None: | |
| # Visualization | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| # Price Chart | |
| fig_price = go.Figure() | |
| fig_price.add_trace(go.Scatter( | |
| x=historical_data.index, | |
| y=historical_data['Close'], | |
| mode='lines', | |
| name='Historical Price' | |
| )) | |
| fig_price.add_trace(go.Scatter( | |
| x=pd.date_range( | |
| start=historical_data.index[-1], | |
| periods=len(predictions)+1 | |
| )[1:], | |
| y=predictions, | |
| mode='lines', | |
| name='Price Forecast' | |
| )) | |
| fig_price.update_layout(title=f'{selected_crypto} Price Forecast') | |
| st.plotly_chart(fig_price) | |
| with col2: | |
| # Technical Indicators | |
| st.subheader("Technical Indicators") | |
| st.write(f"Current RSI: {data_with_indicators['RSI'].iloc[-1]:.2f}") | |
| st.write(f"50-Day SMA: {data_with_indicators['SMA_50'].iloc[-1]:.2f}") | |
| st.write(f"200-Day SMA: {data_with_indicators['SMA_200'].iloc[-1]:.2f}") | |
| st.write(f"MACD: {data_with_indicators['MACD'].iloc[-1]:.2f}") | |
| # Sentiment Analysis Section | |
| st.subheader("๐ง Market Sentiment Analysis") | |
| sentiment_text = st.text_area("Enter recent news or market commentary") | |
| if st.button("Analyze Sentiment"): | |
| if sentiment_text: | |
| sentiment = app.sentiment_analysis(sentiment_text) | |
| if sentiment: | |
| st.write(f"Sentiment: {sentiment['label']}") | |
| st.write(f"Confidence: {sentiment['score']:.2%}") | |
| if __name__ == "__main__": | |
| main() |