File size: 6,654 Bytes
407df81
52e409f
407df81
 
 
52e409f
 
 
070064f
52e409f
070064f
52e409f
 
 
 
 
 
 
070064f
ba9915c
52e409f
 
 
 
 
 
070064f
52e409f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
070064f
52e409f
 
 
 
 
 
 
 
070064f
52e409f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
070064f
52e409f
 
 
 
 
 
 
070064f
 
52e409f
 
 
 
 
070064f
52e409f
 
 
bb9f98e
52e409f
bb9f98e
 
407df81
52e409f
 
 
070064f
52e409f
 
 
070064f
52e409f
 
070064f
52e409f
 
 
 
 
 
ba9915c
52e409f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9915c
52e409f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb9f98e
2862781
070064f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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()