Update app.py
Browse files
app.py
CHANGED
|
@@ -1,81 +1,34 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import plotly.express as px
|
| 5 |
import scipy.optimize as sco
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
-
import requests
|
| 8 |
import random
|
| 9 |
-
import
|
| 10 |
|
| 11 |
def fetch_stock_data(tickers):
|
| 12 |
-
"""Fetch real stock data
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
for ticker in tickers:
|
| 23 |
-
try:
|
| 24 |
-
# Add delay between requests to avoid rate limiting
|
| 25 |
-
time.sleep(1)
|
| 26 |
-
|
| 27 |
-
# Clean up ticker symbol
|
| 28 |
-
clean_ticker = ticker.replace('-', '').strip()
|
| 29 |
-
|
| 30 |
-
querystring = {"symbol": clean_ticker}
|
| 31 |
-
|
| 32 |
-
response = requests.get(url, headers=headers, params=querystring)
|
| 33 |
-
response.raise_for_status()
|
| 34 |
-
data = response.json()
|
| 35 |
-
|
| 36 |
-
# Extract price data
|
| 37 |
-
if "price" in data and "regularMarketPrice" in data["price"]:
|
| 38 |
-
price = data["price"]["regularMarketPrice"]["raw"]
|
| 39 |
-
all_data[ticker] = [price]
|
| 40 |
-
print(f"Successfully fetched data for {ticker}")
|
| 41 |
-
else:
|
| 42 |
-
print(f"No price data found for {ticker}")
|
| 43 |
-
|
| 44 |
-
except requests.exceptions.RequestException as e:
|
| 45 |
-
print(f"Error fetching data for {ticker}: {str(e)}")
|
| 46 |
-
continue
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"Unexpected error for {ticker}: {str(e)}")
|
| 49 |
-
continue
|
| 50 |
-
|
| 51 |
-
if not all_data:
|
| 52 |
-
raise ValueError("No data could be fetched for any ticker")
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
np.random.seed(42) # For reproducibility
|
| 65 |
-
daily_returns = np.random.normal(loc=0.0001, scale=0.02, size=periods)
|
| 66 |
-
prices = np.zeros(periods)
|
| 67 |
-
prices[-1] = current_price
|
| 68 |
-
|
| 69 |
-
for i in range(periods-2, -1, -1):
|
| 70 |
-
prices[i] = prices[i+1] / (1 + daily_returns[i])
|
| 71 |
-
|
| 72 |
-
historical_data[ticker] = prices
|
| 73 |
-
|
| 74 |
-
# Create DataFrame with dates
|
| 75 |
-
dates = pd.date_range(end=datetime.now(), periods=periods)
|
| 76 |
-
historical_df = pd.DataFrame(historical_data, index=dates)
|
| 77 |
-
|
| 78 |
-
return historical_df
|
| 79 |
|
| 80 |
# Predefined S&P 500 Stock List (Sample tickers)
|
| 81 |
SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
|
|
@@ -111,12 +64,14 @@ def simulate_investment(weights, mu, years, initial_investment=10000):
|
|
| 111 |
|
| 112 |
def output_results(risk_level):
|
| 113 |
try:
|
| 114 |
-
#
|
| 115 |
-
selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 5))
|
|
|
|
|
|
|
| 116 |
stocks_df = fetch_stock_data(selected_tickers)
|
| 117 |
|
| 118 |
if stocks_df.empty:
|
| 119 |
-
raise ValueError("
|
| 120 |
|
| 121 |
returns = stocks_df.pct_change().dropna()
|
| 122 |
|
|
@@ -229,4 +184,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
|
|
| 229 |
)
|
| 230 |
|
| 231 |
if __name__ == "__main__":
|
| 232 |
-
app.launch()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
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 |
|
| 11 |
def fetch_stock_data(tickers):
|
| 12 |
+
"""Fetch real stock data using yfinance"""
|
| 13 |
+
try:
|
| 14 |
+
# Download 1 year of data for all tickers at once
|
| 15 |
+
data = yf.download(
|
| 16 |
+
tickers,
|
| 17 |
+
start=(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'),
|
| 18 |
+
end=datetime.now().strftime('%Y-%m-%d'),
|
| 19 |
+
progress=False
|
| 20 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# If only one ticker, the format is different
|
| 23 |
+
if len(tickers) == 1:
|
| 24 |
+
return pd.DataFrame(data['Adj Close'])
|
| 25 |
+
|
| 26 |
+
# Get just the adjusted close prices
|
| 27 |
+
return data['Adj Close']
|
| 28 |
+
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"Error fetching data: {str(e)}")
|
| 31 |
+
raise ValueError(f"Failed to fetch stock data: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# Predefined S&P 500 Stock List (Sample tickers)
|
| 34 |
SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
|
|
|
|
| 64 |
|
| 65 |
def output_results(risk_level):
|
| 66 |
try:
|
| 67 |
+
# Select random tickers
|
| 68 |
+
selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 5))
|
| 69 |
+
|
| 70 |
+
# Fetch real stock data
|
| 71 |
stocks_df = fetch_stock_data(selected_tickers)
|
| 72 |
|
| 73 |
if stocks_df.empty:
|
| 74 |
+
raise ValueError("No stock data received")
|
| 75 |
|
| 76 |
returns = stocks_df.pct_change().dropna()
|
| 77 |
|
|
|
|
| 184 |
)
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
+
app.launch(share=True) # Added share=True to create a public link
|