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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -36
app.py CHANGED
@@ -6,47 +6,51 @@ import plotly.express as px
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 retries"""
14
- max_retries = 3
15
- retry_delay = 2
16
- data_frames = []
17
 
18
- for retry in range(max_retries):
19
  try:
20
- # Try to download data for each ticker individually
21
- for ticker in tickers:
22
- try:
23
- stock = yf.Ticker(ticker)
24
- hist = stock.history(period="1y")
25
- if not hist.empty:
26
- hist.columns = [f"{ticker}_{col}" for col in hist.columns]
27
- data_frames.append(hist[f"{ticker}_Close"])
28
- time.sleep(0.5) # Add delay between requests
29
- except Exception as e:
30
- print(f"Error fetching {ticker}: {str(e)}")
31
- continue
32
 
33
- if data_frames:
34
- # Combine all successful downloads
35
- combined_data = pd.concat(data_frames, axis=1)
36
- combined_data.columns = [col.replace("_Close", "") for col in combined_data.columns]
37
- if not combined_data.empty:
38
- return combined_data
39
-
40
- print(f"Retry {retry + 1}/{max_retries} - No data received")
41
- time.sleep(retry_delay)
42
 
 
 
 
 
 
 
 
 
 
43
  except Exception as e:
44
- print(f"Error during retry {retry + 1}: {str(e)}")
45
- time.sleep(retry_delay)
46
 
47
- # If we reach here, use backup sample data
48
- print("Using backup sample data")
49
- return generate_sample_data(tickers)
 
 
 
 
 
50
 
51
  def generate_sample_data(tickers):
52
  """Generate sample data as backup"""
@@ -62,8 +66,14 @@ def generate_sample_data(tickers):
62
 
63
  return pd.DataFrame(data, index=dates)
64
 
65
- # Predefined S&P 500 Stock List (Sample tickers)
66
- SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
 
 
 
 
 
 
67
 
68
  def calculate_portfolio_metrics(weights, returns):
69
  portfolio_return = np.sum(returns.mean() * weights) * 252
@@ -96,8 +106,8 @@ def simulate_investment(weights, mu, years, initial_investment=10000):
96
 
97
  def output_results(risk_level):
98
  try:
99
- # Select random tickers
100
- selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 5))
101
 
102
  # Fetch real stock data
103
  stocks_df = fetch_stock_data(selected_tickers)
 
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
 
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):
79
  portfolio_return = np.sum(returns.mean() * weights) * 252
 
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)