Update app.py
Browse files
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
|
| 10 |
import time
|
| 11 |
|
| 12 |
def fetch_stock_data(tickers):
|
| 13 |
-
"""Fetch real stock data using
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 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 |
-
|
| 51 |
-
|
| 52 |
-
|
| 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 |
-
#
|
| 70 |
SP500_TICKERS = [
|
| 71 |
'AAPL', # Apple
|
| 72 |
'MSFT', # Microsoft
|
| 73 |
-
'
|
| 74 |
'AMZN', # Amazon
|
| 75 |
-
'TSLA'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 110 |
-
selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS),
|
| 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__":
|
|
|