Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
# crypto_price_prediction.py
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
|
@@ -6,9 +5,7 @@ from torch.optim.lr_scheduler import ReduceLROnPlateau
|
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
import yfinance as yf
|
| 9 |
-
import
|
| 10 |
-
from plotly.subplots import make_subplots
|
| 11 |
-
import gradio as gr
|
| 12 |
from sklearn.preprocessing import MinMaxScaler
|
| 13 |
from datetime import datetime, timedelta
|
| 14 |
import joblib
|
|
@@ -173,10 +170,10 @@ class CryptoAnalyzer:
|
|
| 173 |
model.eval()
|
| 174 |
with torch.no_grad():
|
| 175 |
predictions, confidence = model(X)
|
| 176 |
-
|
| 177 |
-
predictions = self.price_scaler.inverse_transform(
|
| 178 |
-
|
| 179 |
-
actual_prices = self.price_scaler.inverse_transform(
|
| 180 |
rmse = float(np.sqrt(np.mean((actual_prices - predictions) ** 2)))
|
| 181 |
mape = float(np.mean(np.abs((actual_prices - predictions) / actual_prices)) * 100)
|
| 182 |
r2 = float(1 - np.sum((actual_prices - predictions) ** 2) / np.sum((actual_prices - actual_prices.mean()) ** 2))
|
|
@@ -198,172 +195,39 @@ class CryptoAnalyzer:
|
|
| 198 |
except Exception as e:
|
| 199 |
raise ValueError(f"Prediction failed: {str(e)}")
|
| 200 |
|
| 201 |
-
def
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
"Technical Indicators",
|
| 210 |
-
"Model Performance Metrics"
|
| 211 |
-
),
|
| 212 |
-
vertical_spacing=0.1,
|
| 213 |
-
specs=[[{"secondary_y": True}],
|
| 214 |
-
[{"secondary_y": True}],
|
| 215 |
-
[{"secondary_y": True}]]
|
| 216 |
-
)
|
| 217 |
-
confidence_upper = np.array(predictions['predicted']) * (1 + np.array(predictions['confidence']))
|
| 218 |
-
confidence_lower = np.array(predictions['predicted']) * (1 - np.array(predictions['confidence']))
|
| 219 |
-
fig.add_trace(
|
| 220 |
-
go.Scatter(
|
| 221 |
-
x=predictions['dates'],
|
| 222 |
-
y=predictions['actual'],
|
| 223 |
-
name='Actual Price',
|
| 224 |
-
line=dict(color='blue', width=2)
|
| 225 |
-
),
|
| 226 |
-
row=1, col=1
|
| 227 |
-
)
|
| 228 |
-
fig.add_trace(
|
| 229 |
-
go.Scatter(
|
| 230 |
-
x=predictions['dates'],
|
| 231 |
-
y=predictions['predicted'],
|
| 232 |
-
name='Predicted Price',
|
| 233 |
-
line=dict(color='red', width=2)
|
| 234 |
-
),
|
| 235 |
-
row=1, col=1
|
| 236 |
-
)
|
| 237 |
-
fig.add_trace(
|
| 238 |
-
go.Scatter(
|
| 239 |
-
x=predictions['dates'] + predictions['dates'][::-1],
|
| 240 |
-
y=list(confidence_upper) + list(confidence_lower)[::-1],
|
| 241 |
-
fill='toself',
|
| 242 |
-
fillcolor='rgba(255,0,0,0.1)',
|
| 243 |
-
line=dict(color='rgba(255,0,0,0)'),
|
| 244 |
-
name='Confidence Band'
|
| 245 |
-
),
|
| 246 |
-
row=1, col=1
|
| 247 |
-
)
|
| 248 |
-
fig.update_layout(
|
| 249 |
-
height=1200,
|
| 250 |
-
title_text=f"📈 {symbol} Price Analysis Dashboard",
|
| 251 |
-
showlegend=True,
|
| 252 |
-
template="plotly_dark",
|
| 253 |
-
paper_bgcolor='rgba(0,0,0,0)',
|
| 254 |
-
plot_bgcolor='rgba(0,0,0,0)',
|
| 255 |
-
font=dict(size=12)
|
| 256 |
-
)
|
| 257 |
-
summary = f"""
|
| 258 |
-
### 📊 Analysis Summary for {symbol}
|
| 259 |
-
|
| 260 |
-
#### Current Market Status
|
| 261 |
-
- **Current Price:** ${predictions['current_price']:,.2f}
|
| 262 |
-
- **Predicted Next Price:** ${predictions['predicted'][-1]:,.2f}
|
| 263 |
-
- **Expected Change:** {((predictions['predicted'][-1] - predictions['current_price']) / predictions['current_price'] * 100):,.2f}%
|
| 264 |
-
- **24h Volume:** {predictions['volume']:,.0f}
|
| 265 |
-
|
| 266 |
-
#### Technical Indicators
|
| 267 |
-
- **RSI:** {predictions['rsi']:,.2f}
|
| 268 |
-
- **MACD:** {predictions['macd']:,.2f}
|
| 269 |
-
- **Volatility:** {predictions['volatility']:,.2f}%
|
| 270 |
-
|
| 271 |
-
#### Model Performance Metrics
|
| 272 |
-
- **R² Score:** {predictions['r2']:,.4f}
|
| 273 |
-
- **RMSE:** ${predictions['rmse']:,.2f}
|
| 274 |
-
- **MAPE:** {predictions['mape']:,.2f}%
|
| 275 |
-
|
| 276 |
-
#### Prediction Confidence
|
| 277 |
-
- **Average Confidence:** {np.mean(predictions['confidence']) * 100:,.2f}%
|
| 278 |
-
- **Trend Direction:** {'🔺 Upward' if predictions['predicted'][-1] > predictions['actual'][-1] else '🔻 Downward'}
|
| 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 |
-
- Technical indicators analysis
|
| 305 |
-
- Confidence metrics
|
| 306 |
-
- Performance visualization
|
| 307 |
-
""")
|
| 308 |
-
with gr.Row():
|
| 309 |
-
with gr.Column(scale=1):
|
| 310 |
-
crypto_input = gr.Dropdown(
|
| 311 |
-
choices=['BTC', 'ETH', 'BNB', 'XRP', 'ADA', 'SOL', 'DOT', 'DOGE'],
|
| 312 |
-
label="Select Cryptocurrency",
|
| 313 |
-
value="BTC"
|
| 314 |
-
)
|
| 315 |
-
custom_crypto = gr.Textbox(
|
| 316 |
-
label="Or enter custom symbol",
|
| 317 |
-
placeholder="e.g., MATIC"
|
| 318 |
-
)
|
| 319 |
-
with gr.Row():
|
| 320 |
-
days_slider = gr.Slider(
|
| 321 |
-
minimum=30, maximum=365, value=180, step=30,
|
| 322 |
-
label="Historical Days"
|
| 323 |
-
)
|
| 324 |
-
lookback_slider = gr.Slider(
|
| 325 |
-
minimum=7, maximum=60, value=30, step=1,
|
| 326 |
-
label="Lookback Period (Days)"
|
| 327 |
-
)
|
| 328 |
-
submit_btn = gr.Button("📊 Generate Analysis", variant="primary")
|
| 329 |
-
with gr.Column(scale=2):
|
| 330 |
-
plot_output = gr.Plot(label="Analysis Plots")
|
| 331 |
-
with gr.Row():
|
| 332 |
-
analysis_output = gr.Markdown(label="Analysis Summary")
|
| 333 |
-
error_output = gr.Markdown(visible=False)
|
| 334 |
-
def handle_analysis(symbol, custom_symbol, days, lookback):
|
| 335 |
-
try:
|
| 336 |
-
final_symbol = custom_symbol if custom_symbol else symbol
|
| 337 |
-
figure, summary = create_analysis_plots(final_symbol, days, lookback)
|
| 338 |
-
return figure, summary, gr.update(visible=False, value="")
|
| 339 |
-
except Exception as e:
|
| 340 |
-
empty_fig = go.Figure()
|
| 341 |
-
error_msg = f"⚠️ Error during analysis: {str(e)}"
|
| 342 |
-
return empty_fig, "", gr.update(visible=True, value=error_msg)
|
| 343 |
-
submit_btn.click(
|
| 344 |
-
fn=handle_analysis,
|
| 345 |
-
inputs=[crypto_input, custom_crypto, days_slider, lookback_slider],
|
| 346 |
-
outputs=[plot_output, analysis_output, error_output]
|
| 347 |
-
)
|
| 348 |
-
return iface
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
| 351 |
-
|
| 352 |
-
logging.basicConfig(
|
| 353 |
-
level=logging.INFO,
|
| 354 |
-
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 355 |
-
handlers=[
|
| 356 |
-
logging.FileHandler('crypto_predictor.log'),
|
| 357 |
-
logging.StreamHandler()
|
| 358 |
-
]
|
| 359 |
-
)
|
| 360 |
-
try:
|
| 361 |
-
os.makedirs("models", exist_ok=True)
|
| 362 |
-
os.makedirs("cache", exist_ok=True)
|
| 363 |
-
iface = create_interface()
|
| 364 |
-
iface.launch(
|
| 365 |
-
share=False, server_name="0.0.0.0", server_port=7860, debug=True
|
| 366 |
-
)
|
| 367 |
-
except Exception as e:
|
| 368 |
-
logging.error(f"Application failed to start: {str(e)}")
|
| 369 |
-
raise
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import pandas as pd
|
| 7 |
import yfinance as yf
|
| 8 |
+
import streamlit as st
|
|
|
|
|
|
|
| 9 |
from sklearn.preprocessing import MinMaxScaler
|
| 10 |
from datetime import datetime, timedelta
|
| 11 |
import joblib
|
|
|
|
| 170 |
model.eval()
|
| 171 |
with torch.no_grad():
|
| 172 |
predictions, confidence = model(X)
|
| 173 |
+
predictions_reshaped = predictions.cpu().numpy().reshape(-1, 1)
|
| 174 |
+
predictions = self.price_scaler.inverse_transform(predictions_reshaped).flatten()
|
| 175 |
+
y_np_reshaped = y.cpu().numpy().reshape(-1, 1)
|
| 176 |
+
actual_prices = self.price_scaler.inverse_transform(y_np_reshaped).flatten()
|
| 177 |
rmse = float(np.sqrt(np.mean((actual_prices - predictions) ** 2)))
|
| 178 |
mape = float(np.mean(np.abs((actual_prices - predictions) / actual_prices)) * 100)
|
| 179 |
r2 = float(1 - np.sum((actual_prices - predictions) ** 2) / np.sum((actual_prices - actual_prices.mean()) ** 2))
|
|
|
|
| 195 |
except Exception as e:
|
| 196 |
raise ValueError(f"Prediction failed: {str(e)}")
|
| 197 |
|
| 198 |
+
def main():
|
| 199 |
+
st.title("🚀 Cryptocurrency Price Prediction")
|
| 200 |
+
st.sidebar.header("Settings")
|
| 201 |
+
symbol = st.sidebar.selectbox("Select Cryptocurrency", ["BTC", "ETH", "BNB", "XRP", "ADA", "SOL", "DOT", "DOGE"], index=0)
|
| 202 |
+
custom_symbol = st.sidebar.text_input("Or enter custom symbol (e.g., MATIC)", "")
|
| 203 |
+
days = st.sidebar.slider("Historical Days", 30, 365, 180)
|
| 204 |
+
lookback = st.sidebar.slider("Lookback Period (Days)", 7, 60, 30)
|
| 205 |
+
symbol = custom_symbol if custom_symbol else symbol
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
if st.sidebar.button("📊 Generate Analysis"):
|
| 208 |
+
analyzer = CryptoAnalyzer()
|
| 209 |
+
try:
|
| 210 |
+
st.info("Fetching data and generating predictions...")
|
| 211 |
+
predictions = analyzer.get_predictions(symbol, days, lookback)
|
| 212 |
+
|
| 213 |
+
# Display results
|
| 214 |
+
st.subheader("📈 Price Prediction Results")
|
| 215 |
+
st.line_chart({
|
| 216 |
+
"Actual Prices": predictions['actual'],
|
| 217 |
+
"Predicted Prices": predictions['predicted']
|
| 218 |
+
})
|
| 219 |
+
|
| 220 |
+
st.subheader("📊 Model Metrics")
|
| 221 |
+
st.write(f"**R² Score:** {predictions['r2']:.4f}")
|
| 222 |
+
st.write(f"**RMSE:** ${predictions['rmse']:.2f}")
|
| 223 |
+
st.write(f"**MAPE:** {predictions['mape']:.2f}%")
|
| 224 |
+
|
| 225 |
+
st.subheader("🔍 Additional Indicators")
|
| 226 |
+
st.write(f"**RSI:** {predictions['rsi']:.2f}")
|
| 227 |
+
st.write(f"**MACD:** {predictions['macd']:.2f}")
|
| 228 |
+
st.write(f"**Volatility:** {predictions['volatility']:.2f}%")
|
| 229 |
+
except Exception as e:
|
| 230 |
+
st.error(f"⚠️ Error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
if __name__ == "__main__":
|
| 233 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|