Update app.py
Browse files
app.py
CHANGED
|
@@ -6,37 +6,76 @@ import scipy.optimize as sco
|
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
import requests
|
| 8 |
import random
|
| 9 |
-
|
| 10 |
|
| 11 |
def fetch_stock_data(tickers):
|
| 12 |
-
"""Fetch real stock data from Yahoo Finance API"""
|
| 13 |
all_data = {}
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
for ticker in tickers:
|
| 16 |
-
url = "https://yahoo-finance166.p.rapidapi.com/api/v1/finance/quote"
|
| 17 |
-
|
| 18 |
-
querystring = {"symbol": ticker}
|
| 19 |
-
|
| 20 |
-
headers = {
|
| 21 |
-
"X-RapidAPI-Key": "e4d2d5bccdmsh3ad7175fdbb435bp13c65cjsn33c57",
|
| 22 |
-
"X-RapidAPI-Host": "yahoo-finance166.p.rapidapi.com"
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
response = requests.get(url, headers=headers, params=querystring)
|
| 27 |
response.raise_for_status()
|
| 28 |
data = response.json()
|
| 29 |
|
| 30 |
-
# Extract
|
| 31 |
-
if "
|
| 32 |
-
|
| 33 |
-
all_data[ticker] =
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
except
|
| 36 |
print(f"Error fetching data for {ticker}: {str(e)}")
|
| 37 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
return
|
| 40 |
|
| 41 |
# Predefined S&P 500 Stock List (Sample tickers)
|
| 42 |
SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
|
|
|
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
import requests
|
| 8 |
import random
|
| 9 |
+
import time
|
| 10 |
|
| 11 |
def fetch_stock_data(tickers):
|
| 12 |
+
"""Fetch real stock data from Yahoo Finance API with rate limiting"""
|
| 13 |
all_data = {}
|
| 14 |
|
| 15 |
+
url = "https://yahoo-finance166.p.rapidapi.com/stock/v2/get-summary"
|
| 16 |
+
|
| 17 |
+
headers = {
|
| 18 |
+
"X-RapidAPI-Key": "e4d2d5bccdmsh3ad7175fdbb435bp13c65cjsn33c57",
|
| 19 |
+
"X-RapidAPI-Host": "yahoo-finance166.p.rapidapi.com"
|
| 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 |
+
# Create DataFrame with single row of current prices
|
| 55 |
+
df = pd.DataFrame(all_data)
|
| 56 |
+
|
| 57 |
+
# Generate synthetic historical data based on current prices
|
| 58 |
+
periods = 252 # One year of trading days
|
| 59 |
+
historical_data = {}
|
| 60 |
+
|
| 61 |
+
for ticker in df.columns:
|
| 62 |
+
current_price = df[ticker].iloc[0]
|
| 63 |
+
# Generate random walk backwards from current price
|
| 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']
|