Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -5,61 +5,56 @@ import numpy as np
|
|
5 |
from prophet import Prophet
|
6 |
import plotly.graph_objs as go
|
7 |
import math
|
8 |
-
import requests
|
9 |
-
from sklearn.ensemble import RandomForestClassifier
|
10 |
-
from textblob import TextBlob
|
11 |
-
|
12 |
-
|
13 |
-
# --- Replace with your Alpha Vantage API key ---
|
14 |
-
ALPHA_VANTAGE_API_KEY = "YOUR_ALPHA_VANTAGE_API_KEY" # <--- Replace with your key
|
15 |
|
16 |
# --- Constants ---
|
17 |
-
CRYPTO_SYMBOLS = ["
|
18 |
STOCK_SYMBOLS = ["AAPL", "MSFT"]
|
19 |
-
INTERVAL_OPTIONS = ["1h", "
|
20 |
|
21 |
-
# --- Data Fetching Functions ---
|
22 |
def fetch_crypto_data(symbol, interval="1h", limit=100):
|
23 |
-
"""Fetch crypto market data
|
24 |
try:
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
raise Exception(f"Error parsing crypto data: {e}")
|
38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
-
def fetch_stock_data(symbol, interval="
|
41 |
-
"""Fetch stock market data
|
42 |
try:
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
return df.dropna()
|
56 |
-
else:
|
57 |
-
raise Exception(f"Error: Could not retrieve stock data. Check API Key, Symbol, and Interval. Response: {data}")
|
58 |
|
59 |
-
except requests.exceptions.RequestException as e:
|
60 |
-
raise Exception(f"Error fetching stock data: {e}")
|
61 |
-
except (ValueError, KeyError) as e:
|
62 |
-
raise Exception(f"Error parsing stock data: {e}")
|
63 |
|
64 |
def fetch_sentiment_data(keyword): # Placeholder - replace with a real sentiment analysis method
|
65 |
"""Analyze sentiment from social media (placeholder)."""
|
@@ -70,7 +65,7 @@ def fetch_sentiment_data(keyword): # Placeholder - replace with a real sentimen
|
|
70 |
f"{keyword} is amazing!"
|
71 |
]
|
72 |
sentiments = [TextBlob(tweet).sentiment.polarity for tweet in tweets]
|
73 |
-
return sum(sentiments) / len(sentiments)
|
74 |
except Exception as e:
|
75 |
print(f"Sentiment analysis error: {e}")
|
76 |
return 0
|
@@ -330,7 +325,7 @@ with gr.Blocks(theme=gr.themes.Base()) as demo:
|
|
330 |
with gr.Row():
|
331 |
with gr.Column():
|
332 |
market_type_dd = gr.Radio(label="Market Type", choices=["Crypto", "Stock"], value="Crypto")
|
333 |
-
symbol_dd = gr.Dropdown(label="Symbol", choices=CRYPTO_SYMBOLS, value="
|
334 |
interval_dd = gr.Dropdown(label="Interval", choices=INTERVAL_OPTIONS, value="1h")
|
335 |
forecast_steps_slider = gr.Slider(label="Forecast Steps", minimum=1, maximum=100, value=24, step=1)
|
336 |
daily_box = gr.Checkbox(label="Daily Seasonality", value=True)
|
@@ -354,7 +349,7 @@ with gr.Blocks(theme=gr.themes.Base()) as demo:
|
|
354 |
# Event Listener to update symbol dropdown based on market type
|
355 |
def update_symbol_choices(market_type):
|
356 |
if market_type == "Crypto":
|
357 |
-
return gr.Dropdown(choices=CRYPTO_SYMBOLS, value="
|
358 |
elif market_type == "Stock":
|
359 |
return gr.Dropdown(choices=STOCK_SYMBOLS, value="AAPL") # Default to AAPL for stock
|
360 |
return gr.Dropdown(choices=[], value=None) # Shouldn't happen, but safety check
|
|
|
5 |
from prophet import Prophet
|
6 |
import plotly.graph_objs as go
|
7 |
import math
|
8 |
+
import requests
|
9 |
+
from sklearn.ensemble import RandomForestClassifier
|
10 |
+
from textblob import TextBlob
|
11 |
+
import yfinance as yf # Import yfinance
|
|
|
|
|
|
|
12 |
|
13 |
# --- Constants ---
|
14 |
+
CRYPTO_SYMBOLS = ["BTC-USD", "ETH-USD"] # Use standardized symbols
|
15 |
STOCK_SYMBOLS = ["AAPL", "MSFT"]
|
16 |
+
INTERVAL_OPTIONS = ["1h", "1d"] # 1h not available for yfinance for stocks; use 1d for stocks.
|
17 |
|
18 |
+
# --- Data Fetching Functions (Revised) ---
|
19 |
def fetch_crypto_data(symbol, interval="1h", limit=100):
|
20 |
+
"""Fetch crypto market data using yfinance (Yahoo Finance)."""
|
21 |
try:
|
22 |
+
# yfinance uses standardized symbols (e.g., BTC-USD)
|
23 |
+
ticker = yf.Ticker(symbol)
|
24 |
+
# Handle different intervals. Yahoo Finance has limitations.
|
25 |
+
if interval == "1h":
|
26 |
+
period = "1d" # yfinance doesn't support 1h for historical data, so we'll use 1d and resample.
|
27 |
+
df = ticker.history(period=period, interval="1h")
|
28 |
+
elif interval == "1d":
|
29 |
+
df = ticker.history(period="1y", interval=interval) # Get 1 year of data
|
30 |
+
else:
|
31 |
+
raise ValueError("Invalid interval for yfinance.")
|
32 |
+
if df.empty:
|
33 |
+
raise Exception("No data returned from yfinance.")
|
|
|
34 |
|
35 |
+
df.reset_index(inplace=True)
|
36 |
+
df.rename(columns={"Datetime": "timestamp", "Open": "open", "High": "high", "Low": "low", "Close": "close", "Volume": "volume"}, inplace=True)
|
37 |
+
df = df[["timestamp", "open", "high", "low", "close", "volume"]] # Select and order columns
|
38 |
+
return df.dropna()
|
39 |
+
except Exception as e:
|
40 |
+
raise Exception(f"Error fetching crypto data from yfinance: {e}")
|
41 |
|
42 |
+
def fetch_stock_data(symbol, interval="1d"): # Simplified for yfinance
|
43 |
+
"""Fetch stock market data using yfinance."""
|
44 |
try:
|
45 |
+
ticker = yf.Ticker(symbol)
|
46 |
+
df = ticker.history(period="1y", interval=interval) # Get 1 year of daily data
|
47 |
+
|
48 |
+
if df.empty:
|
49 |
+
raise Exception("No data returned from yfinance.")
|
50 |
+
|
51 |
+
df.reset_index(inplace=True)
|
52 |
+
df.rename(columns={"Date": "timestamp", "Open": "open", "High": "high", "Low": "low", "Close": "close", "Volume": "volume"}, inplace=True)
|
53 |
+
df = df[["timestamp", "open", "high", "low", "close", "volume"]]
|
54 |
+
return df.dropna()
|
55 |
+
except Exception as e:
|
56 |
+
raise Exception(f"Error fetching stock data from yfinance: {e}")
|
|
|
|
|
|
|
57 |
|
|
|
|
|
|
|
|
|
58 |
|
59 |
def fetch_sentiment_data(keyword): # Placeholder - replace with a real sentiment analysis method
|
60 |
"""Analyze sentiment from social media (placeholder)."""
|
|
|
65 |
f"{keyword} is amazing!"
|
66 |
]
|
67 |
sentiments = [TextBlob(tweet).sentiment.polarity for tweet in tweets]
|
68 |
+
return sum(sentiments) / len(sentiments) if sentiments else 0 # Avoid ZeroDivisionError
|
69 |
except Exception as e:
|
70 |
print(f"Sentiment analysis error: {e}")
|
71 |
return 0
|
|
|
325 |
with gr.Row():
|
326 |
with gr.Column():
|
327 |
market_type_dd = gr.Radio(label="Market Type", choices=["Crypto", "Stock"], value="Crypto")
|
328 |
+
symbol_dd = gr.Dropdown(label="Symbol", choices=CRYPTO_SYMBOLS, value="BTC-USD") # Use standardized symbols
|
329 |
interval_dd = gr.Dropdown(label="Interval", choices=INTERVAL_OPTIONS, value="1h")
|
330 |
forecast_steps_slider = gr.Slider(label="Forecast Steps", minimum=1, maximum=100, value=24, step=1)
|
331 |
daily_box = gr.Checkbox(label="Daily Seasonality", value=True)
|
|
|
349 |
# Event Listener to update symbol dropdown based on market type
|
350 |
def update_symbol_choices(market_type):
|
351 |
if market_type == "Crypto":
|
352 |
+
return gr.Dropdown(choices=CRYPTO_SYMBOLS, value="BTC-USD")
|
353 |
elif market_type == "Stock":
|
354 |
return gr.Dropdown(choices=STOCK_SYMBOLS, value="AAPL") # Default to AAPL for stock
|
355 |
return gr.Dropdown(choices=[], value=None) # Shouldn't happen, but safety check
|