MacDash commited on
Commit
06772d8
·
verified ·
1 Parent(s): ae46283

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -48
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 # For API calls
9
- from sklearn.ensemble import RandomForestClassifier # For the model
10
- from textblob import TextBlob # For sentiment analysis (optional)
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 = ["BTCUSDT", "ETHUSDT"]
18
  STOCK_SYMBOLS = ["AAPL", "MSFT"]
19
- INTERVAL_OPTIONS = ["1h", "60min"] # Consistent naming
20
 
21
- # --- Data Fetching Functions ---
22
  def fetch_crypto_data(symbol, interval="1h", limit=100):
23
- """Fetch crypto market data from Binance."""
24
  try:
25
- url = f"https://api.binance.com/api/v3/klines"
26
- params = {"symbol": symbol, "interval": interval, "limit": limit}
27
- response = requests.get(url, params=params)
28
- response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
29
- data = response.json()
30
- df = pd.DataFrame(data, columns=["timestamp", "open", "high", "low", "close", "volume"])
31
- df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
32
- df[["open", "high", "low", "close", "volume"]] = df[["open", "high", "low", "close", "volume"]].astype(float)
33
- return df.dropna()
34
- except requests.exceptions.RequestException as e:
35
- raise Exception(f"Error fetching crypto data: {e}")
36
- except (ValueError, KeyError) as e:
37
- raise Exception(f"Error parsing crypto data: {e}")
38
 
 
 
 
 
 
 
39
 
40
- def fetch_stock_data(symbol, interval="60min"):
41
- """Fetch stock market data from Alpha Vantage."""
42
  try:
43
- url = f"https://www.alphavantage.co/query"
44
- params = {"function": "TIME_SERIES_INTRADAY", "symbol": symbol, "interval": interval,
45
- "apikey": ALPHA_VANTAGE_API_KEY}
46
- response = requests.get(url, params=params)
47
- response.raise_for_status() # Raise HTTPError for bad responses
48
- data = response.json()
49
- if "Time Series (60min)" in data: # Check the JSON for the correct key
50
- time_series_data = data["Time Series (60min)"]
51
- df = pd.DataFrame(time_series_data).T.reset_index()
52
- df.columns = ["timestamp", "open", "high", "low", "close", "volume"] # Standardize
53
- df["timestamp"] = pd.to_datetime(df["timestamp"])
54
- df[["open", "high", "low", "close", "volume"]] = df[["open", "high", "low", "close", "volume"]].astype(float)
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) / len(sentiments) if sentiments else 0 # Avoid ZeroDivisionError
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="BTCUSDT") # Start with Crypto
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="BTCUSDT")
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