GLAkavya commited on
Commit
937d618
Β·
verified Β·
1 Parent(s): e726f78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -37
app.py CHANGED
@@ -4,31 +4,17 @@ import numpy as np
4
  import plotly.graph_objects as go
5
  import plotly.express as px
6
  import yfinance as yf
7
- import json
8
  import warnings
9
  warnings.filterwarnings('ignore')
10
 
11
- def load_model():
12
- """Load model from JSON file"""
13
- try:
14
- with open('portfolio_risk_model.json', 'r') as f:
15
- model = json.load(f)
16
- print("βœ… JSON model loaded successfully!")
17
- return model
18
- except Exception as e:
19
- print(f"❌ Model loading failed: {str(e)}")
20
- return None
21
-
22
- class FlexibleRiskApp:
23
  def __init__(self):
24
- self.model = load_model()
25
- # More stock options including the trained ones
26
  self.available_stocks = [
27
- 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', # Trained stocks
28
- 'META', 'NVDA', 'NFLX', 'JPM', 'JNJ', # Additional popular stocks
29
- 'V', 'PG', 'DIS', 'BAC', 'XOM' # More options
30
  ]
31
- print("🎯 Flexible Portfolio Risk Analyzer Ready!")
32
 
33
  def get_stock_data(self, symbols, period='2y'):
34
  """Get stock data with error handling"""
@@ -40,12 +26,14 @@ class FlexibleRiskApp:
40
  return None
41
 
42
  def calculate_portfolio_metrics(self, selected_stocks, days=252, simulations=5000):
43
- """Calculate metrics for any combination of stocks"""
44
  if not selected_stocks:
45
  return None, None
46
 
47
  try:
48
- # Get fresh data for selected stocks
 
 
49
  data = self.get_stock_data(selected_stocks)
50
  if data is None or data.empty:
51
  return None, None
@@ -66,8 +54,6 @@ class FlexibleRiskApp:
66
  if min_eig < 0:
67
  cov_matrix -= 10 * min_eig * np.eye(*cov_matrix.shape)
68
 
69
- print(f"🎯 Running MC simulation for {n_stocks} stock(s): {selected_stocks}")
70
-
71
  # Generate simulation
72
  np.random.seed(42)
73
  L = np.linalg.cholesky(cov_matrix)
@@ -279,10 +265,10 @@ class FlexibleRiskApp:
279
  """
280
 
281
  # Create and launch app
282
- app = FlexibleRiskApp()
283
 
284
  with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
285
- gr.Markdown("# πŸ“Š QuantRisk Pro - Flexible Portfolio Analyzer")
286
  gr.Markdown("**Analyze single stocks or multi-stock portfolios with real-time risk assessment**")
287
 
288
  with gr.Row():
@@ -292,8 +278,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
292
  stock_checkboxes = gr.CheckboxGroup(
293
  choices=app.available_stocks,
294
  value=['AAPL', 'MSFT', 'GOOGL'], # Default selection
295
- label="**Select Stocks (1 or more)**",
296
- info="Choose 1 stock for single analysis or multiple for portfolio"
297
  )
298
 
299
  simulation_days = gr.Slider(
@@ -308,19 +294,18 @@ with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
308
  num_simulations = gr.Dropdown(
309
  choices=[1000, 2500, 5000, 10000],
310
  value=5000,
311
- label="**Number of Simulations**",
312
- info="More simulations = more accuracy"
313
  )
314
 
315
  analyze_btn = gr.Button("πŸš€ Run Risk Analysis", variant="primary", size="lg")
316
 
317
  gr.Markdown("---")
318
  gr.Markdown("""
319
- **πŸ’‘ Usage Tips:**
320
- - βœ… **Single Stock**: Select only 1 stock for individual analysis
321
- - βœ… **Portfolio**: Select 2+ stocks for diversified portfolio
322
- - βœ… **Weights**: Automatically calculated as equal weights
323
- - βœ… **Real Data**: Uses latest market data from Yahoo Finance
324
  """)
325
 
326
  with gr.Column(scale=2):
@@ -330,8 +315,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
330
  value="""
331
  <div style='text-align: center; padding: 50px; background: #f8f9fa; border-radius: 10px;'>
332
  <h3 style='color: #6c757d;'>πŸš€ Ready to Analyze!</h3>
333
- <p>Select stocks and click 'Run Risk Analysis' to see your personalized risk report.</p>
334
- <p><strong>Single stocks and portfolios both supported!</strong></p>
335
  </div>
336
  """
337
  )
@@ -347,7 +331,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
347
  gr.Markdown(
348
  """
349
  <div style="text-align: center; color: #666;">
350
- <p>Built with ❀️ using Gradio | QuantRisk Pro v3.0 | Real-time market data</p>
351
  </div>
352
  """
353
  )
 
4
  import plotly.graph_objects as go
5
  import plotly.express as px
6
  import yfinance as yf
 
7
  import warnings
8
  warnings.filterwarnings('ignore')
9
 
10
+ class SimpleRiskApp:
 
 
 
 
 
 
 
 
 
 
 
11
  def __init__(self):
12
+ # Only 10 reliable stocks with correct names
 
13
  self.available_stocks = [
14
+ 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA',
15
+ 'META', 'NVDA', 'NFLX', 'JPM', 'JNJ'
 
16
  ]
17
+ print("🎯 Simple Portfolio Risk Analyzer Ready!")
18
 
19
  def get_stock_data(self, symbols, period='2y'):
20
  """Get stock data with error handling"""
 
26
  return None
27
 
28
  def calculate_portfolio_metrics(self, selected_stocks, days=252, simulations=5000):
29
+ """Calculate metrics for selected stocks"""
30
  if not selected_stocks:
31
  return None, None
32
 
33
  try:
34
+ print(f"πŸ“Š Analyzing: {selected_stocks}")
35
+
36
+ # Get fresh data
37
  data = self.get_stock_data(selected_stocks)
38
  if data is None or data.empty:
39
  return None, None
 
54
  if min_eig < 0:
55
  cov_matrix -= 10 * min_eig * np.eye(*cov_matrix.shape)
56
 
 
 
57
  # Generate simulation
58
  np.random.seed(42)
59
  L = np.linalg.cholesky(cov_matrix)
 
265
  """
266
 
267
  # Create and launch app
268
+ app = SimpleRiskApp()
269
 
270
  with gr.Blocks(theme=gr.themes.Soft(), title="QuantRisk Pro") as demo:
271
+ gr.Markdown("# πŸ“Š QuantRisk Pro - Portfolio Risk Analyzer")
272
  gr.Markdown("**Analyze single stocks or multi-stock portfolios with real-time risk assessment**")
273
 
274
  with gr.Row():
 
278
  stock_checkboxes = gr.CheckboxGroup(
279
  choices=app.available_stocks,
280
  value=['AAPL', 'MSFT', 'GOOGL'], # Default selection
281
+ label="**Select Stocks (Choose 1 or more)**",
282
+ info="Single stock or portfolio analysis"
283
  )
284
 
285
  simulation_days = gr.Slider(
 
294
  num_simulations = gr.Dropdown(
295
  choices=[1000, 2500, 5000, 10000],
296
  value=5000,
297
+ label="**Number of Simulations**"
 
298
  )
299
 
300
  analyze_btn = gr.Button("πŸš€ Run Risk Analysis", variant="primary", size="lg")
301
 
302
  gr.Markdown("---")
303
  gr.Markdown("""
304
+ **πŸ’‘ How to Use:**
305
+ - Select 1 stock for individual analysis
306
+ - Select 2+ stocks for portfolio analysis
307
+ - Weights automatically calculated as equal
308
+ - Uses real market data from Yahoo Finance
309
  """)
310
 
311
  with gr.Column(scale=2):
 
315
  value="""
316
  <div style='text-align: center; padding: 50px; background: #f8f9fa; border-radius: 10px;'>
317
  <h3 style='color: #6c757d;'>πŸš€ Ready to Analyze!</h3>
318
+ <p>Select stocks and click 'Run Risk Analysis' to see your risk report.</p>
 
319
  </div>
320
  """
321
  )
 
331
  gr.Markdown(
332
  """
333
  <div style="text-align: center; color: #666;">
334
+ <p>Built with ❀️ using Gradio | QuantRisk Pro | Real-time market data</p>
335
  </div>
336
  """
337
  )