kimappl commited on
Commit
4b63b79
·
verified ·
1 Parent(s): 251749f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -15
app.py CHANGED
@@ -1,25 +1,42 @@
1
-
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
 
10
- # Sample stock data generator
11
- def generate_sample_data(tickers, days=252):
12
- np.random.seed(42) # For reproducibility
13
- dates = pd.date_range(end=datetime.now(), periods=days)
14
- data = {}
15
 
16
  for ticker in tickers:
17
- # Generate random walk data
18
- returns = np.random.normal(loc=0.0001, scale=0.02, size=days)
19
- price = 100 * (1 + returns).cumprod()
20
- data[ticker] = price
21
 
22
- return pd.DataFrame(data, index=dates)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # Predefined S&P 500 Stock List (Sample tickers)
25
  SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
@@ -55,9 +72,12 @@ def simulate_investment(weights, mu, years, initial_investment=10000):
55
 
56
  def output_results(risk_level):
57
  try:
58
- # Generate sample data instead of fetching from API
59
- selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 10))
60
- stocks_df = generate_sample_data(selected_tickers)
 
 
 
61
 
62
  returns = stocks_df.pct_change().dropna()
63
 
@@ -125,6 +145,7 @@ def output_results(risk_level):
125
  )
126
 
127
  except Exception as e:
 
128
  return None, None, None, f"Error: {str(e)}", "Error", "Error", None
129
 
130
  # Create Gradio interface
@@ -169,4 +190,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
169
  )
170
 
171
  if __name__ == "__main__":
172
- app.launch()
 
 
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
+ from datetime import datetime, timedelta
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 historical prices
31
+ if "quoteResponse" in data and "result" in data["quoteResponse"]:
32
+ prices = data["quoteResponse"]["result"][0]
33
+ all_data[ticker] = prices["regularMarketPrice"]
34
+
35
+ except Exception as e:
36
+ print(f"Error fetching data for {ticker}: {str(e)}")
37
+ continue
38
+
39
+ return pd.DataFrame(all_data)
40
 
41
  # Predefined S&P 500 Stock List (Sample tickers)
42
  SP500_TICKERS = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'BRK-B', 'NVDA', 'JPM', 'JNJ', 'V']
 
72
 
73
  def output_results(risk_level):
74
  try:
75
+ # Use real data instead of sample data
76
+ selected_tickers = random.sample(SP500_TICKERS, min(len(SP500_TICKERS), 5)) # Reduced to 5 tickers to avoid API limits
77
+ stocks_df = fetch_stock_data(selected_tickers)
78
+
79
+ if stocks_df.empty:
80
+ raise ValueError("Failed to fetch stock data")
81
 
82
  returns = stocks_df.pct_change().dropna()
83
 
 
145
  )
146
 
147
  except Exception as e:
148
+ print(f"Error in output_results: {str(e)}")
149
  return None, None, None, f"Error: {str(e)}", "Error", "Error", None
150
 
151
  # Create Gradio interface
 
190
  )
191
 
192
  if __name__ == "__main__":
193
+ app.launch()