Update app.py
Browse files
app.py
CHANGED
|
@@ -6,43 +6,58 @@ 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 |
-
print(f"No data received for {tickers[0]}")
|
| 28 |
-
return generate_sample_data(tickers)
|
| 29 |
-
return pd.DataFrame(data['Close'])
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 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 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
return generate_sample_data(tickers)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def generate_sample_data(tickers):
|
| 48 |
"""Generate sample data as backup"""
|
|
@@ -58,18 +73,13 @@ def generate_sample_data(tickers):
|
|
| 58 |
|
| 59 |
return pd.DataFrame(data, index=dates)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
SP500_TICKERS = [
|
| 63 |
'AAPL', # Apple
|
| 64 |
'MSFT', # Microsoft
|
| 65 |
-
'
|
| 66 |
'AMZN', # Amazon
|
| 67 |
-
'TSLA'
|
| 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,8 +113,8 @@ def simulate_investment(weights, mu, years, initial_investment=10000):
|
|
| 103 |
|
| 104 |
def output_results(risk_level):
|
| 105 |
try:
|
| 106 |
-
# Select random tickers
|
| 107 |
-
selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS),
|
| 108 |
|
| 109 |
# Fetch real stock data
|
| 110 |
stocks_df = fetch_stock_data(selected_tickers)
|
|
@@ -223,3 +233,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
|
|
| 223 |
)
|
| 224 |
|
| 225 |
if __name__ == "__main__":
|
|
|
|
|
|
| 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"
|
| 15 |
+
BASE_URL = "https://www.alphavantage.co/query"
|
| 16 |
+
all_data = {}
|
| 17 |
+
|
| 18 |
+
for ticker in tickers:
|
| 19 |
+
try:
|
| 20 |
+
# Use TIME_SERIES_DAILY for daily data
|
| 21 |
+
params = {
|
| 22 |
+
"function": "TIME_SERIES_DAILY",
|
| 23 |
+
"symbol": ticker,
|
| 24 |
+
"apikey": API_KEY,
|
| 25 |
+
"outputsize": "full"
|
| 26 |
+
}
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
print(f"Fetching data for {ticker}...")
|
| 29 |
+
response = requests.get(BASE_URL, params=params)
|
| 30 |
+
response.raise_for_status()
|
| 31 |
+
data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
if "Time Series (Daily)" in data:
|
| 34 |
+
daily_data = data["Time Series (Daily)"]
|
| 35 |
+
# Convert to DataFrame
|
| 36 |
+
df = pd.DataFrame.from_dict(daily_data, orient='index')
|
| 37 |
+
df = df.astype(float)
|
| 38 |
+
# Use adjusted close price
|
| 39 |
+
all_data[ticker] = df['4. close'].iloc[:252] # Get last year of data
|
| 40 |
+
print(f"Successfully fetched data for {ticker}")
|
| 41 |
+
else:
|
| 42 |
+
print(f"No data found for {ticker}")
|
| 43 |
+
if "Note" in data:
|
| 44 |
+
print("API Message:", data["Note"])
|
| 45 |
+
|
| 46 |
+
# Add delay between requests (Alpha Vantage has a rate limit)
|
| 47 |
+
time.sleep(12) # 12 second delay between requests
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error fetching {ticker}: {str(e)}")
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
if not all_data:
|
| 54 |
+
print("No data received, using backup data")
|
| 55 |
return generate_sample_data(tickers)
|
| 56 |
+
|
| 57 |
+
# Combine all data and align dates
|
| 58 |
+
df = pd.DataFrame(all_data)
|
| 59 |
+
df = df.sort_index(ascending=True)
|
| 60 |
+
return df
|
| 61 |
|
| 62 |
def generate_sample_data(tickers):
|
| 63 |
"""Generate sample data as backup"""
|
|
|
|
| 73 |
|
| 74 |
return pd.DataFrame(data, index=dates)
|
| 75 |
|
| 76 |
+
# Updated S&P 500 Stock List (reduced number due to API rate limits)
|
| 77 |
SP500_TICKERS = [
|
| 78 |
'AAPL', # Apple
|
| 79 |
'MSFT', # Microsoft
|
| 80 |
+
'GOOGL', # Google
|
| 81 |
'AMZN', # Amazon
|
| 82 |
+
'TSLA' # Tesla
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
]
|
| 84 |
|
| 85 |
def calculate_portfolio_metrics(weights, returns):
|
|
|
|
| 113 |
|
| 114 |
def output_results(risk_level):
|
| 115 |
try:
|
| 116 |
+
# Select random tickers (reduced number due to API rate limits)
|
| 117 |
+
selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 3))
|
| 118 |
|
| 119 |
# Fetch real stock data
|
| 120 |
stocks_df = fetch_stock_data(selected_tickers)
|
|
|
|
| 233 |
)
|
| 234 |
|
| 235 |
if __name__ == "__main__":
|
| 236 |
+
app.launch()
|