kimappl commited on
Commit
01faba1
·
verified ·
1 Parent(s): 0747659

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -45
app.py CHANGED
@@ -6,51 +6,43 @@ import plotly.express as px
6
  import scipy.optimize as sco
7
  from datetime import datetime, timedelta
8
  import random
9
- import requests
10
  import time
11
 
12
  def fetch_stock_data(tickers):
13
- """Fetch real stock data using Alpha Vantage API"""
14
- API_KEY = "Y86RZ52NQ8YVX7F6" # Should be in environment variable in production
15
- BASE_URL = "https://www.alphavantage.co/query"
16
- all_data = {}
17
-
18
- for ticker in tickers:
19
- try:
20
- # Add delay to respect rate limits (5 API calls per minute for free tier)
21
- time.sleep(12) # 12 second delay between calls
22
-
23
- params = {
24
- "function": "TIME_SERIES_DAILY_ADJUSTED",
25
- "symbol": ticker,
26
- "outputsize": "full",
27
- "apikey": API_KEY
28
- }
 
29
 
30
- response = requests.get(BASE_URL, params=params)
31
- data = response.json()
 
 
 
 
 
 
 
32
 
33
- if "Time Series (Daily)" in data:
34
- # Convert the time series data to DataFrame
35
- df = pd.DataFrame.from_dict(data["Time Series (Daily)"], orient="index")
36
- df = df.astype(float)
37
- all_data[ticker] = df["4. close"].iloc[:252] # Get last year of data
38
- print(f"Successfully fetched data for {ticker}")
39
- else:
40
- print(f"No data found for {ticker}")
41
-
42
- except Exception as e:
43
- print(f"Error fetching {ticker}: {str(e)}")
44
- continue
45
-
46
- if not all_data:
47
- print("No data received, using backup data")
48
- return generate_sample_data(tickers)
49
 
50
- # Combine all data and align dates
51
- df = pd.DataFrame(all_data)
52
- df = df.sort_index(ascending=True)
53
- return df
54
 
55
  def generate_sample_data(tickers):
56
  """Generate sample data as backup"""
@@ -66,13 +58,18 @@ def generate_sample_data(tickers):
66
 
67
  return pd.DataFrame(data, index=dates)
68
 
69
- # Updated S&P 500 Stock List (reduced number due to API rate limits)
70
  SP500_TICKERS = [
71
  'AAPL', # Apple
72
  'MSFT', # Microsoft
73
- 'GOOGL', # Google
74
  'AMZN', # Amazon
75
- 'TSLA' # Tesla
 
 
 
 
 
76
  ]
77
 
78
  def calculate_portfolio_metrics(weights, returns):
@@ -106,8 +103,8 @@ def simulate_investment(weights, mu, years, initial_investment=10000):
106
 
107
  def output_results(risk_level):
108
  try:
109
- # Select random tickers (reduced number due to API rate limits)
110
- selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 3))
111
 
112
  # Fetch real stock data
113
  stocks_df = fetch_stock_data(selected_tickers)
@@ -226,4 +223,3 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
226
  )
227
 
228
  if __name__ == "__main__":
229
- app.launch()
 
6
  import scipy.optimize as sco
7
  from datetime import datetime, timedelta
8
  import random
9
+ import yfinance as yf
10
  import time
11
 
12
  def fetch_stock_data(tickers):
13
+ """Fetch real stock data using yfinance with better error handling"""
14
+ try:
15
+ # Download data for all tickers at once
16
+ data = yf.download(
17
+ tickers,
18
+ start=(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'),
19
+ end=datetime.now().strftime('%Y-%m-%d'),
20
+ group_by='ticker',
21
+ auto_adjust=True
22
+ )
23
+
24
+ # If only one ticker is passed, the data format is different
25
+ if len(tickers) == 1:
26
+ if data.empty:
27
+ print(f"No data received for {tickers[0]}")
28
+ return generate_sample_data(tickers)
29
+ return pd.DataFrame(data['Close'])
30
 
31
+ # For multiple tickers, extract just the Close prices
32
+ close_prices = pd.DataFrame()
33
+ for ticker in tickers:
34
+ if (ticker, 'Close') in data.columns:
35
+ close_prices[ticker] = data[ticker]['Close']
36
+
37
+ if close_prices.empty:
38
+ print("No data received for any ticker")
39
+ return generate_sample_data(tickers)
40
 
41
+ return close_prices
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ except Exception as e:
44
+ print(f"Error fetching data: {str(e)}")
45
+ return generate_sample_data(tickers)
 
46
 
47
  def generate_sample_data(tickers):
48
  """Generate sample data as backup"""
 
58
 
59
  return pd.DataFrame(data, index=dates)
60
 
61
+ # Predefined S&P 500 Stock List (Sample tickers)
62
  SP500_TICKERS = [
63
  'AAPL', # Apple
64
  'MSFT', # Microsoft
65
+ 'GOOG', # Google
66
  'AMZN', # Amazon
67
+ 'TSLA', # Tesla
68
+ 'NVDA', # NVIDIA
69
+ 'META', # Meta
70
+ 'BRK-B', # Berkshire Hathaway
71
+ 'JPM', # JPMorgan Chase
72
+ 'V' # Visa
73
  ]
74
 
75
  def calculate_portfolio_metrics(weights, returns):
 
103
 
104
  def output_results(risk_level):
105
  try:
106
+ # Select random tickers
107
+ selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 5))
108
 
109
  # Fetch real stock data
110
  stocks_df = fetch_stock_data(selected_tickers)
 
223
  )
224
 
225
  if __name__ == "__main__":