File size: 18,618 Bytes
3be1304
f9b094e
 
9afaf57
b2faade
3be1304
f9b094e
3be1304
 
b2faade
3be1304
 
9afaf57
3be1304
 
a383b89
 
 
3be1304
8581ec0
0a4a922
 
19488d2
 
0a4a922
ae0dbb8
 
 
 
19488d2
 
ae0dbb8
 
 
 
49ffddb
3be1304
a383b89
3be1304
 
 
49ffddb
3be1304
49ffddb
 
 
3be1304
a383b89
d74ee1c
a383b89
d74ee1c
a383b89
 
 
 
 
 
 
 
 
 
3be1304
49ffddb
3be1304
a383b89
 
 
49ffddb
3be1304
 
 
49ffddb
3be1304
a383b89
3be1304
8581ec0
3be1304
050bc2d
 
0a4a922
050bc2d
 
 
 
 
 
 
 
 
 
 
 
f496524
5e5c364
 
 
050bc2d
5e5c364
050bc2d
5e5c364
 
050bc2d
5e5c364
 
 
050bc2d
5e5c364
 
 
050bc2d
5e5c364
 
 
 
050bc2d
5e5c364
 
050bc2d
5e5c364
 
 
050bc2d
5e5c364
 
 
050bc2d
5e5c364
 
8bb7281
050bc2d
8bb7281
050bc2d
8581ec0
d01194b
ae0dbb8
d74ee1c
 
19488d2
ae0dbb8
19488d2
 
 
d74ee1c
 
 
eebf529
19488d2
d74ee1c
ae0dbb8
19488d2
d74ee1c
 
 
 
 
 
 
 
a383b89
 
d74ee1c
a383b89
 
8bb7281
d74ee1c
a383b89
 
8bb7281
a383b89
 
 
8bb7281
a383b89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb7281
a383b89
9afaf57
d74ee1c
 
 
 
ae0dbb8
d74ee1c
 
 
 
 
 
 
ae0dbb8
d74ee1c
 
 
ae0dbb8
 
72fe0f0
ae0dbb8
72fe0f0
 
ae0dbb8
 
72fe0f0
 
d74ee1c
 
 
eebf529
d74ee1c
e11bacb
d74ee1c
 
e11bacb
 
72fe0f0
d74ee1c
 
 
 
 
 
 
 
 
72fe0f0
d74ee1c
 
adcb633
d74ee1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
050bc2d
d74ee1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9afaf57
a383b89
 
 
 
8bb7281
a383b89
8bb7281
a383b89
 
 
 
 
 
8bb7281
3be1304
a383b89
 
 
 
3be1304
 
a383b89
 
 
3be1304
a383b89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb7281
a383b89
 
 
 
 
 
8bb7281
a383b89
3be1304
a383b89
 
3be1304
 
 
a383b89
3be1304
8bb7281
3be1304
 
a383b89
3be1304
 
8bb7281
f9b094e
 
 
8bb7281
 
 
 
 
 
 
 
 
 
 
d74ee1c
 
 
8bb7281
 
a383b89
8bb7281
 
 
 
 
 
 
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import os
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
import numpy as np
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import gradio as gr
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta
from typing import Tuple, Dict
import joblib
import warnings
import ta
from tqdm import tqdm

warnings.filterwarnings('ignore')

class PriceScaler:
    def __init__(self):
        self.scaler = MinMaxScaler()
        
    def fit_transform(self, data):
        # Ensure data is 2D for fitting
        data_2d = np.array(data).reshape(-1, 1)
        # Transform and return 1D array
        return self.scaler.fit_transform(data_2d).flatten()
        
    def inverse_transform(self, data):
        # Ensure data is 2D for inverse transform
        data_2d = np.array(data).reshape(-1, 1)
        # Transform and return 1D array
        return self.scaler.inverse_transform(data_2d).flatten()

class CryptoPredictor(nn.Module):
    def __init__(self, input_dim: int, hidden_dim: int = 128, num_layers: int = 2, dropout: float = 0.2):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers

        self.lstm = nn.LSTM(
            input_dim,
            hidden_dim,
            num_layers=num_layers,
            batch_first=True,
            dropout=dropout if num_layers > 1 else 0,
            bidirectional=True
        )
        self.bn = nn.BatchNorm1d(hidden_dim * 2)
        self.fc = nn.Sequential(
            nn.Linear(hidden_dim * 2, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, 1)
        )
        self.confidence_fc = nn.Sequential(
            nn.Linear(hidden_dim * 2, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, 1),
            nn.Sigmoid()
        )

    def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        batch_size = x.size(0)
        h0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_dim).to(x.device)
        c0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_dim).to(x.device)

        lstm_out, _ = self.lstm(x, (h0, c0))
        last_hidden = lstm_out[:, -1, :]
        normalized_hidden = self.bn(last_hidden)

        prediction = self.fc(normalized_hidden)
        confidence = self.confidence_fc(normalized_hidden)
        return prediction, confidence

class CryptoAnalyzer:
    def __init__(self, model_dir: str = "models", cache_dir: str = "cache"):
        self.scaler = MinMaxScaler()
        self.price_scaler = PriceScaler()
        self.model_dir = model_dir
        self.cache_dir = cache_dir
        os.makedirs(model_dir, exist_ok=True)
        os.makedirs(cache_dir, exist_ok=True)
        
        self.feature_columns = [
            'Open', 'High', 'Low', 'Close', 'Volume', 'Returns', 'Volatility',
            'MA5', 'MA20', 'RSI', 'Price_Momentum', 'Volume_Momentum', 'MACD',
            'BB_upper', 'BB_lower', 'Stoch_K', 'Stoch_D', 'ADX', 'ATR'
        ]
        
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        
    def get_data(self, symbol: str, days: int) -> pd.DataFrame:
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days + 30)  # Extra 30 days for indicators
        
        df = yf.download(f"{symbol}-USD", start=start_date, end=end_date, progress=False)
        
        if df.empty:
            raise ValueError(f"No data available for {symbol}")
        
        # Calculate basic features
        df['Returns'] = df['Close'].pct_change()
        df['Volatility'] = df['Returns'].rolling(window=20).std()
        
        # Moving averages
        df['MA5'] = df['Close'].rolling(window=5).mean()
        df['MA20'] = df['Close'].rolling(window=20).mean()
        
        # Technical indicators
        df['RSI'] = ta.momentum.rsi(df['Close'])
        df['Price_Momentum'] = ta.momentum.roc(df['Close'])
        df['Volume_Momentum'] = ta.momentum.roc(df['Volume'])
        
        macd = ta.trend.macd(df['Close'])
        df['MACD'] = macd.iloc[:, 0]
        
        bollinger = ta.volatility.BollingerBands(df['Close'])
        df['BB_upper'] = bollinger.bollinger_hband()
        df['BB_lower'] = bollinger.bollinger_lband()
        
        stoch = ta.momentum.StochasticOscillator(df['High'], df['Low'], df['Close'])
        df['Stoch_K'] = stoch.stoch()
        df['Stoch_D'] = stoch.stoch_signal()
        
        df['ADX'] = ta.trend.adx(df['High'], df['Low'], df['Close'])
        df['ATR'] = ta.volatility.average_true_range(df['High'], df['Low'], df['Close'])
        
        df = df.dropna()
        
        return df.iloc[-days:]

    def prepare_data(self, df: pd.DataFrame, lookback: int) -> Tuple[torch.Tensor, torch.Tensor]:
        # Scale features
        features = df[self.feature_columns].values
        scaled_features = self.scaler.fit_transform(features)
    
        # Scale close prices - ensure 1D output
        close_prices = df['Close'].values
        scaled_close = self.price_scaler.fit_transform(close_prices)
    
        X, y = [], []
        for i in range(len(df) - lookback):
            X.append(scaled_features[i:(i + lookback)])
            y.append(scaled_close[i + lookback])
    
        X = torch.FloatTensor(np.array(X)).to(self.device)
        y = torch.FloatTensor(np.array(y)).reshape(-1).to(self.device)
    
        return X, y

    def get_model_path(self, symbol: str) -> str:
        return os.path.join(self.model_dir, f"{symbol.lower()}_model.pth")
    
    def get_scaler_path(self, symbol: str) -> str:
        return os.path.join(self.model_dir, f"{symbol.lower()}_scaler.pkl")

    def train_model(self, X: torch.Tensor, y: torch.Tensor, symbol: str) -> CryptoPredictor:
        model = CryptoPredictor(X.shape[2]).to(self.device)
        criterion = nn.HuberLoss()
        optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=0.01)
        scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5, verbose=True)
        
        batch_size = min(32, len(X) // 4)
        dataset = torch.utils.data.TensorDataset(X, y)
        train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)
        
        best_loss = float('inf')
        patience = 10
        patience_counter = 0
        
        model.train()
        with tqdm(range(50), desc=f"Training {symbol} model") as pbar:
            for epoch in pbar:
                total_loss = 0
                for batch_X, batch_y in train_loader:
                    optimizer.zero_grad()
                    predictions, _ = model(batch_X)
                    loss = criterion(predictions, batch_y)
                    loss.backward()
                    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
                    optimizer.step()
                    total_loss += loss.item()
                
                avg_loss = total_loss / len(train_loader)
                scheduler.step(avg_loss)
                pbar.set_postfix({'loss': f'{avg_loss:.6f}'})
                
                if avg_loss < best_loss:
                    best_loss = avg_loss
                    patience_counter = 0
                    torch.save(model.state_dict(), self.get_model_path(symbol))
                else:
                    patience_counter += 1
                    if patience_counter >= patience:
                        break
        
        return model

    def get_predictions(self, symbol: str, days: int, lookback: int) -> Dict:
        try:
            df = self.get_data(symbol, days)
            X, y = self.prepare_data(df, lookback)

            model_path = self.get_model_path(symbol)
            if os.path.exists(model_path):
                model = CryptoPredictor(X.shape[2]).to(self.device)
                model.load_state_dict(torch.load(model_path))
            else:
                model = self.train_model(X, y, symbol)
                joblib.dump(self.scaler, self.get_scaler_path(symbol))

            model.eval()
            with torch.no_grad():
                predictions, confidence = model(X)
                predictions = predictions.cpu().numpy().flatten()  # Ensure 1D
                confidence = confidence.cpu().numpy().flatten()  # Ensure 1D
            
                # Inverse transform predictions
                predictions = self.price_scaler.inverse_transform(predictions)
            
                # Inverse transform actual values
                y_np = y.cpu().numpy().flatten()  # Ensure 1D
                actual_prices = self.price_scaler.inverse_transform(y_np)
        
            rmse = float(np.sqrt(np.mean((actual_prices - predictions) ** 2)))
            mape = float(np.mean(np.abs((actual_prices - predictions) / actual_prices)) * 100)
            r2 = float(1 - np.sum((actual_prices - predictions) ** 2) / np.sum((actual_prices - actual_prices.mean()) ** 2))
            
            dates = df.index[lookback:].strftime('%Y-%m-%d').tolist()
        
            return {
                'dates': dates,
                'actual': actual_prices.tolist(),
                'predicted': predictions.tolist(),
                'confidence': confidence.flatten().tolist(),
                'rmse': rmse,
                'mape': mape,
                'r2': r2,
                'volatility': float(df['Volatility'].mean() * 100),
                'current_price': float(df['Close'].iloc[-1]),
                'volume': float(df['Volume'].iloc[-1]),
                'rsi': float(df['RSI'].iloc[-1]),
                'macd': float(df['MACD'].iloc[-1])
            }
    
        except Exception as e:
            raise ValueError(f"Prediction failed: {str(e)}")
    
def create_analysis_plots(symbol: str, days: int = 180, lookback: int = 30) -> Tuple[go.Figure, str]:
    try:
        analyzer = CryptoAnalyzer()
        predictions = analyzer.get_predictions(symbol, days, lookback)
        
        fig = make_subplots(
            rows=3, cols=1,
            subplot_titles=(
                f"{symbol} Price Prediction with Confidence Bands",
                "Technical Indicators",
                "Model Performance Metrics"
            ),
            vertical_spacing=0.1,
            specs=[[{"secondary_y": True}],
                  [{"secondary_y": True}],
                  [{"secondary_y": True}]]
        )
        
        confidence_upper = np.array(predictions['predicted']) * (1 + np.array(predictions['confidence']))
        confidence_lower = np.array(predictions['predicted']) * (1 - np.array(predictions['confidence']))
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=predictions['actual'],
                name='Actual Price',
                line=dict(color='blue', width=2)
            ),
            row=1, col=1
        )
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=predictions['predicted'],
                name='Predicted Price',
                line=dict(color='red', width=2)
            ),
            row=1, col=1
        )
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'] + predictions['dates'][::-1],
                y=list(confidence_upper) + list(confidence_lower)[::-1],
                fill='toself',
                fillcolor='rgba(255,0,0,0.1)',
                line=dict(color='rgba(255,0,0,0)'),
                name='Confidence Band'
            ),
            row=1, col=1
        )
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=predictions['confidence'],
                name='Model Confidence',
                line=dict(color='green', width=2)
            ),
            row=2, col=1
        )
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=[70] * len(predictions['dates']),
                line=dict(color='red', dash='dash'),
                name='RSI Overbought',
                showlegend=False
            ),
            row=2, col=1,
            secondary_y=True
        )
        
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=[30] * len(predictions['dates']),
                line=dict(color='green', dash='dash'),
                name='RSI Oversold',
                showlegend=False
            ),
            row=2, col=1,
            secondary_y=True
        )
        
        error = np.array(predictions['actual']) - np.array(predictions['predicted'])
        fig.add_trace(
            go.Scatter(
                x=predictions['dates'],
                y=error.tolist(),
                name='Prediction Error',
                line=dict(color='orange', width=2)
            ),
            row=3, col=1
        )
        
        fig.update_layout(
            height=1200,
            title_text=f"πŸ“ˆ {symbol} Price Analysis Dashboard",
            showlegend=True,
            template="plotly_dark",
            paper_bgcolor='rgba(0,0,0,0)',
            plot_bgcolor='rgba(0,0,0,0)',
            font=dict(size=12)
        )
        
        fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(128,128,128,0.2)')
        fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(128,128,128,0.2)')
        
        summary = f"""
### πŸ“Š Analysis Summary for {symbol}

#### Current Market Status
- **Current Price:** ${predictions['current_price']:,.2f}
- **Predicted Next Price:** ${predictions['predicted'][-1]:,.2f}
- **Expected Change:** {((predictions['predicted'][-1] - predictions['current_price']) / predictions['current_price'] * 100):,.2f}%
- **24h Volume:** {predictions['volume']:,.0f}

#### Technical Indicators
- **RSI:** {predictions['rsi']:,.2f}
- **MACD:** {predictions['macd']:,.2f}
- **Volatility:** {predictions['volatility']:,.2f}%

# Continuing from previous summary string
#### Model Performance Metrics
- **RΒ² Score:** {predictions['r2']:,.4f}
- **RMSE:** ${predictions['rmse']:,.2f}
- **MAPE:** {predictions['mape']:,.2f}%

#### Prediction Confidence
- **Average Confidence:** {np.mean(predictions['confidence']) * 100:,.2f}%
- **Trend Direction:** {'πŸ”Ί Upward' if predictions['predicted'][-1] > predictions['actual'][-1] else 'πŸ”» Downward'}

> *Note: Past performance does not guarantee future results. This analysis is for informational purposes only.*
        """
        
        return fig, summary
        
    except Exception as e:
        fig = go.Figure()
        fig.add_annotation(
            text=str(e),
            xref="paper",
            yref="paper",
            x=0.5,
            y=0.5,
            showarrow=False
        )
        return fig, f"⚠️ Error: {str(e)}"

def create_interface():
    with gr.Blocks(theme=gr.themes.Soft()) as iface:
        gr.Markdown("""
        # πŸš€ Advanced Cryptocurrency Price Prediction
        
        This app uses deep learning to predict cryptocurrency prices and provide comprehensive market analysis.
        
        ### Features:
        - Real-time price predictions
        - Technical indicators analysis
        - Confidence metrics
        - Performance visualization
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                crypto_input = gr.Dropdown(
                    choices=['BTC', 'ETH', 'BNB', 'XRP', 'ADA', 'SOL', 'DOT', 'DOGE'],
                    label="Select Cryptocurrency",
                    value="BTC"
                )
                custom_crypto = gr.Textbox(
                    label="Or enter custom symbol",
                    placeholder="e.g., MATIC"
                )
                
                with gr.Row():
                    days_slider = gr.Slider(
                        minimum=30,
                        maximum=365,
                        value=180,
                        step=30,
                        label="Historical Days"
                    )
                    lookback_slider = gr.Slider(
                        minimum=7,
                        maximum=60,
                        value=30,
                        step=1,
                        label="Lookback Period (Days)"
                    )
                
                submit_btn = gr.Button("πŸ“Š Generate Analysis", variant="primary")
                
            with gr.Column(scale=2):
                plot_output = gr.Plot(label="Analysis Plots")
                
        with gr.Row():
            analysis_output = gr.Markdown(label="Analysis Summary")
            error_output = gr.Markdown(visible=False)
        
        gr.Markdown("""
        ### πŸ“ˆ Tips for best results:
        - Use longer historical periods for stable coins
        - Shorter lookback periods work better for volatile markets
        - Consider market conditions when interpreting predictions
        """)
        
        def handle_analysis(symbol, custom_symbol, days, lookback):
            try:
                final_symbol = custom_symbol if custom_symbol else symbol
                figure, summary = create_analysis_plots(final_symbol, days, lookback)
                return figure, summary, gr.update(visible=False, value="")
            except Exception as e:
                empty_fig = go.Figure()
                error_msg = f"⚠️ Error during analysis: {str(e)}"
                return empty_fig, "", gr.update(visible=True, value=error_msg)
        
        submit_btn.click(
            fn=handle_analysis,
            inputs=[crypto_input, custom_crypto, days_slider, lookback_slider],
            outputs=[plot_output, analysis_output, error_output]
        )
    
    return iface

if __name__ == "__main__":
    import logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('crypto_predictor.log'),
            logging.StreamHandler()
        ]
    )
    
    try:
        os.makedirs("models", exist_ok=True)
        os.makedirs("cache", exist_ok=True)
        
        iface = create_interface()
        iface.launch(
            share=False,
            server_name="0.0.0.0",
            server_port=7860,
            debug=True
        )
    except Exception as e:
        logging.error(f"Application failed to start: {str(e)}")
        raise