DanielKiani commited on
Commit
1c44875
ยท
verified ยท
1 Parent(s): 58fc99b

Update scripts/app.py

Browse files
Files changed (1) hide show
  1. scripts/app.py +128 -217
scripts/app.py CHANGED
@@ -10,17 +10,45 @@ import os
10
  import sys
11
  import json
12
  import torch
13
- from fetch_market_data import fetch_market_data, ASSETS, FRED_IDS
14
- from llm_analysis_rag import analyze_agent_decision, analyze_historical_segment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  from stable_baselines3 import SAC
16
- from environment import PortfolioEnv
 
 
17
  from scripts.evaluate_baselines import buy_and_hold, equally_weighted_rebalanced
18
 
19
  # --- Configuration ---
20
- MODEL_PATH = os.path.join("checkpoints", "sac_portfolio_model.zip")
21
  WINDOW_SIZE = 30
22
  MACRO_COLS = list(FRED_IDS.values())
23
- DASHBOARD_DATA_PATH = os.path.join("data", "historical_dashboard_data.csv")
24
 
25
  # *** UPDATE THESE DATES TO MATCH YOUR ACTUAL TRAINING PERIOD ***
26
  TRAIN_START_DATE = "2015-01-01"
@@ -70,6 +98,7 @@ def initialize_dashboard_data():
70
 
71
  # Initialize data at startup
72
  try:
 
73
  initialize_dashboard_data()
74
  except Exception as e:
75
  print(f"Warning: Data initialization failed. Error: {e}")
@@ -85,7 +114,7 @@ def evaluate_agent_pro(env, model):
85
  """
86
  obs, info = env.reset()
87
  terminated, truncated = False, False
88
- portfolio_values = [env.initial_amount]
89
 
90
  while not (terminated or truncated):
91
  action, _states = model.predict(obs, deterministic=True)
@@ -144,6 +173,11 @@ def calculate_feature_importance(model, obs):
144
  """
145
  # Convert observation to torch tensor and enable gradient tracking
146
  obs_tensor = torch.as_tensor(obs, dtype=torch.float32, device=model.device)
 
 
 
 
 
147
  obs_tensor.requires_grad_()
148
 
149
  # Get the policy network (actor)
@@ -164,28 +198,24 @@ def calculate_feature_importance(model, obs):
164
  action_mean = actor(scaled_input)
165
 
166
  # We need a scalar output to calculate gradients against.
167
- # Here we sum, representing overall sensitivity of the action vector.
168
  target_output = action_mean.sum()
169
 
170
  # Calculate gradients of the target output with respect to the input features
171
  grad = torch.autograd.grad(outputs=target_output, inputs=scaled_input)[0]
172
  grads.append(grad)
173
 
174
- # Average the gradients using the trapezoidal rule approximation
175
- avg_grads = (grads[:-1] + grads[1:]) / 2.0
176
- avg_grads = torch.stack(avg_grads).mean(dim=0)
 
177
 
178
  # Calculate Integrated Gradients: (input - baseline) * average_gradients
179
  integrated_grads = (obs_tensor - baseline) * avg_grads
180
 
181
- # Detach, move to cpu, and convert to numpy array
182
  importance_scores = integrated_grads.detach().cpu().numpy().flatten()
183
 
184
  # Feature Names mapping
185
- num_assets = len(ASSETS)
186
- num_macro = len(MACRO_COLS)
187
-
188
- # Create feature names based on the observation structure
189
  feature_names = []
190
  for i in range(WINDOW_SIZE):
191
  for asset in ASSETS:
@@ -223,76 +253,72 @@ def calculate_feature_importance(model, obs):
223
  yaxis={'categoryorder':'total ascending'},
224
  coloraxis_showscale=False,
225
  margin=dict(l=10, r=10, t=40, b=10),
226
- height=300 # Keep it compact
 
 
 
 
 
 
 
227
  )
228
 
229
  return fig
230
 
231
  # =========================================
232
- # Tab 4 Logic: Historical Simulation (UPDATED)
233
  # =========================================
234
 
235
  def run_historical_simulation(start_date_str, end_date_str):
236
- """
237
- Runs the RL agent on historical data and compares to baselines using professional metrics.
238
- """
239
  if DASHBOARD_DATA_DF is None:
240
- return go.Figure(), "Data not initialized. Please restart app.", gr.update(visible=False)
241
 
242
  status_msg = "Preparing simulation..."
243
- yield go.Figure(), status_msg, gr.update(visible=False)
244
 
245
  try:
246
- # 1. Validate and Slice Data
247
  try:
248
  start_date = pd.to_datetime(start_date_str)
249
  end_date = pd.to_datetime(end_date_str)
250
  except ValueError:
251
- yield go.Figure(), "Error: Invalid date format. Use YYYY-MM-DD.", gr.update(visible=False)
252
  return
253
 
254
  if start_date < DASHBOARD_DATA_DF.index.min() or end_date > DASHBOARD_DATA_DF.index.max():
255
  avail_start = DASHBOARD_DATA_DF.index.min().date()
256
  avail_end = DASHBOARD_DATA_DF.index.max().date()
257
- yield go.Figure(), f"Error: Selected dates outside available range ({avail_start} to {avail_end}).", gr.update(visible=False)
258
  return
259
 
260
  df_slice = DASHBOARD_DATA_DF.loc[start_date:end_date].copy()
261
  asset_cols_only = [c for c in ASSETS if c in df_slice.columns]
262
 
263
  if len(df_slice) < WINDOW_SIZE + 10:
264
- yield go.Figure(), "Error: Time period too short for simulation.", gr.update(visible=False)
265
  return
266
 
267
- # 2. Setup Environment and Agent
268
  status_msg = "Running RL Agent simulation..."
269
- yield go.Figure(), status_msg, gr.update(visible=False)
270
 
271
- env = PortfolioEnv(df_slice, WINDOW_SIZE, initial_amount=10000)
272
 
273
  if not os.path.exists(MODEL_PATH):
274
  raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
275
  model = SAC.load(MODEL_PATH)
276
 
277
- # 3. Run Simulation Loop & Get Values using Pro Function
278
  rl_portfolio_series = evaluate_agent_pro(env, model)
279
 
280
- # 4. Calculate Baselines using Pro Functions
281
- status_msg = "Calculating baselines and metrics..."
282
- yield go.Figure(), status_msg, gr.update(visible=False)
283
 
284
- # Pass only asset columns to baseline functions
285
- bnh_portfolio_series = buy_and_hold(df_slice[asset_cols_only], initial_amount=10000)
286
- # Realign B&H index to match RL agent's start date
287
  bnh_portfolio_series = bnh_portfolio_series.loc[rl_portfolio_series.index[0]:]
288
- # Normalize B&H starting value to match RL agent's start
289
  bnh_portfolio_series = bnh_portfolio_series / bnh_portfolio_series.iloc[0] * 10000
290
 
291
- eq_portfolio_series = equally_weighted_rebalanced(df_slice[asset_cols_only], initial_amount=10000)
292
  eq_portfolio_series = eq_portfolio_series.loc[rl_portfolio_series.index[0]:]
293
  eq_portfolio_series = eq_portfolio_series / eq_portfolio_series.iloc[0] * 10000
294
 
295
- # 5. Generate Plot
296
  fig = go.Figure()
297
  fig.add_trace(go.Scatter(x=rl_portfolio_series.index, y=rl_portfolio_series, mode='lines', name='RL Agent (SAC)', line=dict(color='#10b981', width=3)))
298
  fig.add_trace(go.Scatter(x=bnh_portfolio_series.index, y=bnh_portfolio_series, mode='lines', name='Buy & Hold (SPY)', line=dict(color='#6b7280', dash='dash')))
@@ -306,15 +332,14 @@ def run_historical_simulation(start_date_str, end_date_str):
306
  paper_bgcolor='rgba(0,0,0,0)',
307
  plot_bgcolor='rgba(0,0,0,0)',
308
  hovermode="x unified",
309
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
 
310
  )
311
 
312
- # 6. Calculate Professional Metrics Table
313
  rl_m = calculate_metrics_pro(rl_portfolio_series)
314
  bnh_m = calculate_metrics_pro(bnh_portfolio_series)
315
  eq_m = calculate_metrics_pro(eq_portfolio_series)
316
 
317
- # Helper to format based on metric type
318
  def fmt(val, is_pct=True):
319
  if pd.isna(val): return "N/A"
320
  return f"{val:.2%}" if is_pct else f"{val:.2f}"
@@ -327,16 +352,12 @@ def run_historical_simulation(start_date_str, end_date_str):
327
  }
328
  metrics_df = pd.DataFrame(metrics_data)
329
 
330
- # Format the dataframe as a markdown table for cleaner display
331
- metrics_md = metrics_df.to_markdown(index=False)
332
- final_metrics_display = f"### ๐Ÿ“Š Professional Performance Metrics\n\n{metrics_md}"
333
-
334
- yield fig, "Simulation Complete.", final_metrics_display
335
 
336
  except Exception as e:
337
  import traceback
338
  traceback.print_exc()
339
- yield go.Figure(), f"Error during simulation: {str(e)}", gr.update(visible=False)
340
 
341
 
342
  # =========================================
@@ -344,7 +365,6 @@ def run_historical_simulation(start_date_str, end_date_str):
344
  # =========================================
345
 
346
  def run_historical_analysis(selected_assets, period_name):
347
- """Backend for Tab 3."""
348
  if DASHBOARD_DATA_DF is None or not selected_assets:
349
  return go.Figure(), "Please wait for data initialization or select assets."
350
 
@@ -352,27 +372,25 @@ def run_historical_analysis(selected_assets, period_name):
352
  yield go.Figure(), status_html
353
 
354
  try:
355
- # 1. Filter Data by Time Period
356
  days = TIME_PERIODS.get(period_name, 365)
357
  cutoff_date = datetime.now() - timedelta(days=days)
358
  valid_assets = [a for a in selected_assets if a in DASHBOARD_DATA_DF.columns]
359
  if not valid_assets:
360
- yield go.Figure(), "Error: Selected assets not found in available data."
361
  return
362
  df_filtered = DASHBOARD_DATA_DF.loc[cutoff_date:, valid_assets].copy()
363
  if df_filtered.empty:
364
- yield go.Figure(), f"No data found for the selected period: {period_name}"
365
  return
366
 
367
- # 2. Generate Normalized Price Plot
368
  df_normalized = df_filtered / df_filtered.iloc[0] * 100
369
  fig = px.line(df_normalized, x=df_normalized.index, y=df_normalized.columns,
370
  title=f"Performance Comparison: {period_name} (Base=100)",
371
  color_discrete_sequence=px.colors.qualitative.Bold)
372
  fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
373
- yaxis_title="Normalized Price", xaxis_title="Date", legend_title_text="", hovermode="x unified")
 
374
 
375
- # 3. Run AI Analysis
376
  analysis_text = analyze_historical_segment(df_filtered, valid_assets, period_name)
377
  formatted_analysis = f"### ๐Ÿค– AI Analyst Report: {period_name}\n\n{analysis_text}"
378
  yield fig, formatted_analysis
@@ -380,25 +398,24 @@ def run_historical_analysis(selected_assets, period_name):
380
  except Exception as e:
381
  import traceback
382
  traceback.print_exc()
383
- yield go.Figure(), f"### Error during analysis\n\n{str(e)}"
384
 
385
 
386
  # =========================================
387
- # Tab 2 Logic: Forecast & Analysis (XAI)
388
  # =========================================
389
 
390
  def get_latest_data_window(window_size=30):
391
- """Fetches latest data needed for prediction."""
392
  print("Fetching prediction data...")
393
  lookback_days = window_size + 150
394
  end_date = datetime.now().strftime('%Y-%m-%d')
395
  start_date = (datetime.now() - timedelta(days=lookback_days)).strftime('%Y-%m-%d')
396
- temp_filename = os.path.join("data", "temp_gradio_prediction_data.csv")
397
  fetch_market_data(start_date, end_date, temp_filename)
398
  if not os.path.exists(temp_filename): raise Exception("Failed to fetch market data file.")
399
  df = pd.read_csv(temp_filename, index_col=0, parse_dates=True)
400
  df.dropna(inplace=True)
401
- if len(df) < window_size: raise Exception(f"Not enough clean data fetched for prediction.")
402
  return df.iloc[-window_size:].copy()
403
 
404
  def prepare_observation(data_window):
@@ -407,30 +424,24 @@ def prepare_observation(data_window):
407
  norm_prices = price_data / (price_data[0] + 1e-8)
408
  norm_macro = macro_data / (macro_data[0] + 1e-8)
409
  obs = np.concatenate([norm_prices, norm_macro], axis=1)
410
- # Return both flattened obs for model and raw obs for XAI
411
  return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
412
 
413
  def predict_and_analyze():
414
- """Main function for Forecast Tab."""
415
  status_msg = "Starting process..."
416
  loading_html = """<div style="color: #9ca3af;">๐Ÿ”„ Fetching data & running prediction...</div>"""
417
- # Update to yield an empty plot for the XAI chart initially
418
  yield status_msg, None, go.Figure(), loading_html
419
 
420
  try:
421
  data_window = get_latest_data_window(WINDOW_SIZE)
422
- # Get flattened obs for prediction and raw obs for XAI
423
  flat_obs, raw_obs, df_window_for_analyst = prepare_observation(data_window)
424
 
425
  if not os.path.exists(MODEL_PATH): raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
426
  model = SAC.load(MODEL_PATH)
427
 
428
- # --- XAI: Calculate Feature Importance ---
429
  status_msg = "Calculating feature importance..."
430
  yield status_msg, None, go.Figure(), loading_html
431
- xai_plot = calculate_feature_importance(model, raw_obs)
432
 
433
- # --- Prediction ---
434
  action, _ = model.predict(flat_obs, deterministic=True)
435
  exp_action = np.exp(np.asarray(action).flatten())
436
  weights = exp_action / np.sum(exp_action)
@@ -441,7 +452,6 @@ def predict_and_analyze():
441
 
442
  status_msg = "Prediction done. Running AI Risk Analysis..."
443
  analysing_html = """<div style="color: #9ca3af;">๐Ÿค– Running Qwen-2.5-3B Risk Analysis...</div>"""
444
- # Yield XAI plot along with other outputs
445
  yield status_msg, alloc_df, xai_plot, analysing_html
446
 
447
  allocations_for_llm = {k: float(v) for k, v in allocations_dict.items()}
@@ -453,18 +463,12 @@ def predict_and_analyze():
453
  risk = analysis_result.get('risk_level', 'N/A').upper()
454
  just = analysis_result.get('justification', 'N/A')
455
  conf = analysis_result.get('confidence_score', 'N/A')
456
- if 'HIGH' in risk:
457
- risk_css = "color: #ef4444; font-weight: bold;"
458
- status_bg = "#7f1d1d"
459
- status_border = "#ef4444"
460
- status_icon = "โ›”"
461
- status_text = "TRADE BLOCKED: High Risk Detected"
462
- else:
463
- risk_css = "color: #10b981; font-weight: bold;"
464
- status_bg = "#064e3b"
465
- status_border = "#10b981"
466
- status_icon = "๐Ÿš€"
467
- status_text = "TRADE APPROVED"
468
 
469
  report_html = f"""
470
  <div style="background-color: #1f2937; padding: 20px; border-radius: 12px 12px 0 0; border: 1px solid #374151; border-bottom: none;">
@@ -479,53 +483,38 @@ def predict_and_analyze():
479
  </div>"""
480
  else:
481
  report_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Analysis Failed to Parse</h3><p>{str(analysis_result)}</p></div>"""
482
- # Final yield with all outputs including XAI plot
483
  yield status_msg, alloc_df, xai_plot, report_html
484
  except Exception as e:
485
  import traceback
486
  traceback.print_exc()
487
- status_msg = f"Error: {str(e)}"
488
- error_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Process Error</h3><p>{str(e)}</p></div>"""
489
- # Final yield in case of error
490
- yield status_msg, None, go.Figure(), error_html
491
-
492
 
493
  # =========================================
494
  # Tab 1 Logic: Live Dashboard (DUMMY DATA)
495
  # =========================================
496
  def get_dashboard_metrics():
497
  return "$135,400", "+3.07%"
498
-
499
  def get_portfolio_history_plot():
500
  dates = pd.date_range(start="2023-01-01", periods=100)
501
  np.random.seed(42)
502
- rl_returns = np.random.normal(0.001, 0.01, 100)
503
- bnh_returns = np.random.normal(0.0005, 0.012, 100)
504
- rl_value = 10000 * np.cumprod(1 + rl_returns)
505
- bnh_value = 10000 * np.cumprod(1 + bnh_returns)
506
  fig = go.Figure()
507
- fig.add_trace(go.Scatter(x=dates, y=rl_value, mode='lines', name='RL Agent (Live)', line=dict(color='#10b981', width=3)))
508
  fig.add_trace(go.Scatter(x=dates, y=bnh_value, mode='lines', name='Benchmark', line=dict(color='#6b7280', dash='dash')))
509
- fig.update_layout(title="Portfolio Net Worth (Live Tracking)", xaxis_title="Date", yaxis_title="Net Worth ($)", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))
510
  return fig
511
-
512
  def get_current_allocation_plot():
513
- labels = ASSETS + ['Cash']
514
- values = [0.25, 0.10, 0.30, 0.15, 0.05, 0.15]
515
- fig = px.pie(values=values, names=labels, title="Current Holdings Breakdown", color_discrete_sequence=px.colors.qualitative.Bold)
516
- fig.update_traces(textposition='inside', textinfo='percent+label', hole=.4)
517
- fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', legend=dict(orientation="h", yanchor="bottom", y=-0.1))
518
  return fig
519
-
520
  def get_recent_transactions():
521
- data = [["2025-11-24", "Rebalance", "MULTIPLE", "N/A"], ["2025-11-24", "SELL", "SPY", "$4,500"], ["2025-11-24", "BUY", "TLT", "$4,200"], ["2025-11-21", "BUY", "BTC-USD", "$1,000"]]
522
- return pd.DataFrame(data, columns=["Date", "Type", "Asset", "Approx. Value"])
523
-
524
 
525
  # =========================================
526
  # Gradio Interface
527
  # =========================================
528
-
529
  custom_css = """
530
  .metric-box { background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151; text-align: center; }
531
  .metric-label { font-size: 1.1em; color: #9ca3af; margin-bottom: 5px; }
@@ -533,133 +522,55 @@ custom_css = """
533
  .disclaimer-box { background-color: #374151; padding: 15px; border-radius: 8px; border-left: 4px solid #f59e0b; color: #d1d5db; font-size: 0.9em; margin-bottom: 20px; }
534
  """
535
 
536
- # theme = gr.themes.Soft(primary_hue="emerald", secondary_hue="slate", neutral_hue="zinc").set(
537
- # body_background_fill="#111827", block_background_fill="#1f2937", block_border_width="1px", block_border_color="#374151"
538
- # )
539
-
540
- with gr.Blocks(
541
- # theme=theme,
542
- # css=custom_css,
543
- title="Deep RL Portfolio Manager") as demo:
544
- gr.HTML("""<script>function forceDark(){document.body.classList.add('dark');} forceDark(); setTimeout(forceDark, 500);</script>""")
545
-
546
  gr.Markdown("# ๐Ÿง  Deep RL & LLM Portfolio Manager")
547
 
548
  with gr.Tabs():
549
- # ================= TAB 1: DASHBOARD (RESTORED) =================
550
- with gr.TabItem("๐Ÿ“Š Live Dashboard"):
551
- # Metrics Row
552
  with gr.Row():
553
- # MOVED THIS LINE INSIDE THE TAB
554
- nw_val, dc_val = get_dashboard_metrics()
555
- with gr.Column(elem_classes=["metric-box"]):
556
- gr.HTML(f"<div class='metric-label'>Current Net Worth</div><div class='metric-value'>{nw_val}</div>")
557
- with gr.Column(elem_classes=["metric-box"]):
558
- gr.HTML(f"<div class='metric-label'>24h Change</div><div class='metric-value' style='color: #10b981;'>{daily_change}</div>")
559
-
560
- # Main Chart row
561
  with gr.Row():
562
- with gr.Column(scale=3):
563
- history_chart = gr.Plot(value=get_portfolio_history_plot(), label="Net Worth History")
564
-
565
- # Bottom Row: Allocations and Transactions
566
  with gr.Row():
567
- with gr.Column(scale=1):
568
- allocation_chart = gr.Plot(value=get_current_allocation_plot(), label="Current Allocation")
569
- with gr.Column(scale=2):
570
- gr.Markdown("### Recent Transactions")
571
- transactions_table = gr.Dataframe(value=get_recent_transactions(), interactive=False, wrap=True)
572
-
573
- # ================= TAB 2: FORECAST (UPDATED with XAI) =================
574
- with gr.TabItem("๐Ÿ”ฎ Forecast & AI Analysis"):
575
- gr.Markdown("### Generate Tomorrow's Portfolio Strategy")
576
- run_btn = gr.Button("๐Ÿš€ Run Overnight Analysis", variant="primary", size="lg")
577
- status_output = gr.Textbox(label="System Status", placeholder="Ready...", interactive=False, lines=1)
578
- gr.Markdown("---")
579
-
580
  with gr.Row():
581
- # Left Column: Allocations & XAI Plot
582
  with gr.Column(scale=2):
583
- gr.Markdown("### ๐Ÿ“ˆ Suggested Position")
584
- allocation_output = gr.Dataframe(headers=["Asset", "Allocation"], datatype=["str", "str"], interactive=False)
585
-
586
- # NEW: XAI Feature Importance Plot
587
- gr.Markdown("### ๐Ÿง  Why did the agent choose this?")
588
- xai_output_plot = gr.Plot(label="Top Influential Factors (XAI)", show_label=False)
589
-
590
- # Right Column: AI Analysis Report
591
  with gr.Column(scale=3):
592
- analysis_report_html = gr.HTML(label="AI Risk Analysis Report")
593
-
594
- # Updated click event with new XAI output
595
- run_btn.click(
596
- fn=predict_and_analyze,
597
- inputs=None,
598
- outputs=[status_output, allocation_output, xai_output_plot, analysis_report_html]
599
- )
600
-
601
- # ================= TAB 3: HISTORICAL DATA ANALYST =================
602
- with gr.TabItem("๐Ÿ“… Historical Data Analyst"):
603
- gr.Markdown("### Analyze Past Market Performance with AI")
604
-
605
- with gr.Row():
606
- with gr.Column(scale=1):
607
- all_tickers_hist = ASSETS + list(FRED_IDS.values())
608
- if DASHBOARD_DATA_DF is not None:
609
- available_tickers_hist = [t for t in all_tickers_hist if t in DASHBOARD_DATA_DF.columns]
610
- else:
611
- available_tickers_hist = []
612
- default_tickers_hist = available_tickers_hist[:3] if available_tickers_hist else []
613
-
614
- asset_selector = gr.Dropdown(choices=available_tickers_hist, value=default_tickers_hist, multiselect=True, label="1. Select Assets")
615
- period_selector = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="2. Select Period")
616
- analyze_btn = gr.Button("๐Ÿ”Ž Run Analysis", variant="primary")
617
-
618
- with gr.Column(scale=3):
619
- historical_plot = gr.Plot(label="Performance Plot")
620
-
621
- gr.Markdown("---")
622
- historical_analysis_md = gr.Markdown("### ๐Ÿค– AI Analyst Report\n\n*Click 'Run Analysis' to generate.*")
623
-
624
- analyze_btn.click(
625
- fn=run_historical_analysis,
626
- inputs=[asset_selector, period_selector],
627
- outputs=[historical_plot, historical_analysis_md]
628
- )
629
-
630
- # ================= TAB 4: HISTORICAL SIMULATION (UPDATED with Pro Metrics) =================
631
- with gr.TabItem("๐Ÿ”™ Historical Simulation"):
632
- gr.Markdown("### Backtest the RL Agent against Baselines")
633
-
634
- # Disclaimer Box
635
- gr.HTML(f"""
636
- <div class='disclaimer-box'>
637
- <strong>โš ๏ธ IMPORTANT DISCLAIMER:</strong> The RL model was trained on data from approximately
638
- <strong>{TRAIN_START_DATE} to {TRAIN_END_DATE}</strong>. Running simulations outside or overlapping significantly
639
- with this period may not accurately reflect real-world performance (lookahead bias or out-of-distribution data).
640
- Use for educational purposes only.
641
- </div>
642
- """)
643
 
 
644
  with gr.Row():
645
  with gr.Column(scale=1):
646
- start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'))
647
- end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
648
- sim_btn = gr.Button("โ–ถ๏ธ Run Simulation", variant="primary")
649
- sim_status = gr.Textbox(label="Status", interactive=False, lines=1)
650
-
651
  with gr.Column(scale=3):
652
- sim_plot = gr.Plot(label="Simulation Performance")
 
 
653
 
654
- gr.Markdown("---")
655
- # Updated to Markdown component for better table formatting
656
- sim_metrics_md = gr.Markdown("### ๐Ÿ“Š Professional Performance Metrics\n\n*Run simulation to see metrics.*")
657
-
658
- sim_btn.click(
659
- fn=run_historical_simulation,
660
- inputs=[start_date_input, end_date_input],
661
- outputs=[sim_plot, sim_status, sim_metrics_md]
662
- )
663
 
664
  if __name__ == "__main__":
665
  demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, share=True)
 
10
  import sys
11
  import json
12
  import torch
13
+ import shutil
14
+ import yfinance as yf
15
+
16
+ # --- Fix YFinance Cache Lock ---
17
+ try:
18
+ cache_dir = "/tmp/pytz_cache"
19
+ if os.path.exists(cache_dir): shutil.rmtree(cache_dir)
20
+ os.makedirs(cache_dir, exist_ok=True)
21
+ yf.set_tz_cache_location(cache_dir)
22
+ except: pass
23
+
24
+ # --- Add project root to sys.path ---
25
+ try:
26
+ script_dir = os.path.dirname(os.path.abspath(__file__))
27
+ project_root = os.path.dirname(script_dir)
28
+ if project_root not in sys.path:
29
+ sys.path.insert(0, project_root)
30
+ except NameError:
31
+ project_root = os.getcwd()
32
+ if project_root not in sys.path:
33
+ sys.path.insert(0, project_root)
34
+
35
+ print(f"Project Root set to: {project_root}")
36
+
37
+ # --- Imports ---
38
+ from scripts.fetch_market_data import fetch_market_data, ASSETS, FRED_IDS
39
+ # Import the new analysis function instead of RAG tools
40
+ from scripts.llm_analysis_rag import analyze_agent_decision, analyze_historical_segment, setup_rag_chain
41
  from stable_baselines3 import SAC
42
+ # Import the environment for simulation
43
+ from scripts.environment import PortfolioEnv
44
+ # Import baseline functions
45
  from scripts.evaluate_baselines import buy_and_hold, equally_weighted_rebalanced
46
 
47
  # --- Configuration ---
48
+ MODEL_PATH = os.path.join(project_root, "checkpoints", "sac_portfolio_model.zip")
49
  WINDOW_SIZE = 30
50
  MACRO_COLS = list(FRED_IDS.values())
51
+ DASHBOARD_DATA_PATH = os.path.join(project_root, "data", "historical_dashboard_data.csv")
52
 
53
  # *** UPDATE THESE DATES TO MATCH YOUR ACTUAL TRAINING PERIOD ***
54
  TRAIN_START_DATE = "2015-01-01"
 
98
 
99
  # Initialize data at startup
100
  try:
101
+ setup_rag_chain() # Initialize RAG components if needed
102
  initialize_dashboard_data()
103
  except Exception as e:
104
  print(f"Warning: Data initialization failed. Error: {e}")
 
114
  """
115
  obs, info = env.reset()
116
  terminated, truncated = False, False
117
+ portfolio_values = [env.initial_balance]
118
 
119
  while not (terminated or truncated):
120
  action, _states = model.predict(obs, deterministic=True)
 
173
  """
174
  # Convert observation to torch tensor and enable gradient tracking
175
  obs_tensor = torch.as_tensor(obs, dtype=torch.float32, device=model.device)
176
+
177
+ # Ensure batch dimension exists
178
+ if obs_tensor.dim() == 1:
179
+ obs_tensor = obs_tensor.unsqueeze(0)
180
+
181
  obs_tensor.requires_grad_()
182
 
183
  # Get the policy network (actor)
 
198
  action_mean = actor(scaled_input)
199
 
200
  # We need a scalar output to calculate gradients against.
 
201
  target_output = action_mean.sum()
202
 
203
  # Calculate gradients of the target output with respect to the input features
204
  grad = torch.autograd.grad(outputs=target_output, inputs=scaled_input)[0]
205
  grads.append(grad)
206
 
207
+ # Stack and average gradients
208
+ stacked_grads = torch.stack(grads)
209
+ avg_grads = (stacked_grads[:-1] + stacked_grads[1:]) / 2.0
210
+ avg_grads = avg_grads.mean(dim=0)
211
 
212
  # Calculate Integrated Gradients: (input - baseline) * average_gradients
213
  integrated_grads = (obs_tensor - baseline) * avg_grads
214
 
215
+ # Detach, move to cpu, flatten, and convert to numpy array
216
  importance_scores = integrated_grads.detach().cpu().numpy().flatten()
217
 
218
  # Feature Names mapping
 
 
 
 
219
  feature_names = []
220
  for i in range(WINDOW_SIZE):
221
  for asset in ASSETS:
 
253
  yaxis={'categoryorder':'total ascending'},
254
  coloraxis_showscale=False,
255
  margin=dict(l=10, r=10, t=40, b=10),
256
+ height=300, # Keep it compact
257
+ # Style the hover labels for readability
258
+ hoverlabel=dict(
259
+ bgcolor="white",
260
+ font_size=14,
261
+ font_family="Roboto",
262
+ font_color="black"
263
+ )
264
  )
265
 
266
  return fig
267
 
268
  # =========================================
269
+ # Tab 4 Logic: Historical Simulation
270
  # =========================================
271
 
272
  def run_historical_simulation(start_date_str, end_date_str):
 
 
 
273
  if DASHBOARD_DATA_DF is None:
274
+ return go.Figure(), "Data not initialized. Please restart app.", None
275
 
276
  status_msg = "Preparing simulation..."
277
+ yield go.Figure(), status_msg, None
278
 
279
  try:
 
280
  try:
281
  start_date = pd.to_datetime(start_date_str)
282
  end_date = pd.to_datetime(end_date_str)
283
  except ValueError:
284
+ yield go.Figure(), "Error: Invalid date format. Use YYYY-MM-DD.", None
285
  return
286
 
287
  if start_date < DASHBOARD_DATA_DF.index.min() or end_date > DASHBOARD_DATA_DF.index.max():
288
  avail_start = DASHBOARD_DATA_DF.index.min().date()
289
  avail_end = DASHBOARD_DATA_DF.index.max().date()
290
+ yield go.Figure(), f"Error: Dates out of range ({avail_start} to {avail_end}).", None
291
  return
292
 
293
  df_slice = DASHBOARD_DATA_DF.loc[start_date:end_date].copy()
294
  asset_cols_only = [c for c in ASSETS if c in df_slice.columns]
295
 
296
  if len(df_slice) < WINDOW_SIZE + 10:
297
+ yield go.Figure(), "Error: Time period too short.", None
298
  return
299
 
 
300
  status_msg = "Running RL Agent simulation..."
301
+ yield go.Figure(), status_msg, None
302
 
303
+ env = PortfolioEnv(df_slice, WINDOW_SIZE, initial_balance=10000)
304
 
305
  if not os.path.exists(MODEL_PATH):
306
  raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
307
  model = SAC.load(MODEL_PATH)
308
 
 
309
  rl_portfolio_series = evaluate_agent_pro(env, model)
310
 
311
+ status_msg = "Calculating baselines..."
312
+ yield go.Figure(), status_msg, None
 
313
 
314
+ bnh_portfolio_series = buy_and_hold(df_slice[asset_cols_only], initial_balance=10000)
 
 
315
  bnh_portfolio_series = bnh_portfolio_series.loc[rl_portfolio_series.index[0]:]
 
316
  bnh_portfolio_series = bnh_portfolio_series / bnh_portfolio_series.iloc[0] * 10000
317
 
318
+ eq_portfolio_series = equally_weighted_rebalanced(df_slice[asset_cols_only], initial_balance=10000)
319
  eq_portfolio_series = eq_portfolio_series.loc[rl_portfolio_series.index[0]:]
320
  eq_portfolio_series = eq_portfolio_series / eq_portfolio_series.iloc[0] * 10000
321
 
 
322
  fig = go.Figure()
323
  fig.add_trace(go.Scatter(x=rl_portfolio_series.index, y=rl_portfolio_series, mode='lines', name='RL Agent (SAC)', line=dict(color='#10b981', width=3)))
324
  fig.add_trace(go.Scatter(x=bnh_portfolio_series.index, y=bnh_portfolio_series, mode='lines', name='Buy & Hold (SPY)', line=dict(color='#6b7280', dash='dash')))
 
332
  paper_bgcolor='rgba(0,0,0,0)',
333
  plot_bgcolor='rgba(0,0,0,0)',
334
  hovermode="x unified",
335
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
336
+ hoverlabel=dict(bgcolor="white", font_size=14, font_family="Roboto", font_color="black")
337
  )
338
 
 
339
  rl_m = calculate_metrics_pro(rl_portfolio_series)
340
  bnh_m = calculate_metrics_pro(bnh_portfolio_series)
341
  eq_m = calculate_metrics_pro(eq_portfolio_series)
342
 
 
343
  def fmt(val, is_pct=True):
344
  if pd.isna(val): return "N/A"
345
  return f"{val:.2%}" if is_pct else f"{val:.2f}"
 
352
  }
353
  metrics_df = pd.DataFrame(metrics_data)
354
 
355
+ yield fig, "Simulation Complete.", metrics_df
 
 
 
 
356
 
357
  except Exception as e:
358
  import traceback
359
  traceback.print_exc()
360
+ yield go.Figure(), f"Error: {str(e)}", None
361
 
362
 
363
  # =========================================
 
365
  # =========================================
366
 
367
  def run_historical_analysis(selected_assets, period_name):
 
368
  if DASHBOARD_DATA_DF is None or not selected_assets:
369
  return go.Figure(), "Please wait for data initialization or select assets."
370
 
 
372
  yield go.Figure(), status_html
373
 
374
  try:
 
375
  days = TIME_PERIODS.get(period_name, 365)
376
  cutoff_date = datetime.now() - timedelta(days=days)
377
  valid_assets = [a for a in selected_assets if a in DASHBOARD_DATA_DF.columns]
378
  if not valid_assets:
379
+ yield go.Figure(), "Error: Selected assets not found."
380
  return
381
  df_filtered = DASHBOARD_DATA_DF.loc[cutoff_date:, valid_assets].copy()
382
  if df_filtered.empty:
383
+ yield go.Figure(), f"No data found for: {period_name}"
384
  return
385
 
 
386
  df_normalized = df_filtered / df_filtered.iloc[0] * 100
387
  fig = px.line(df_normalized, x=df_normalized.index, y=df_normalized.columns,
388
  title=f"Performance Comparison: {period_name} (Base=100)",
389
  color_discrete_sequence=px.colors.qualitative.Bold)
390
  fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
391
+ yaxis_title="Normalized Price", xaxis_title="Date", legend_title_text="", hovermode="x unified",
392
+ hoverlabel=dict(bgcolor="white", font_size=14, font_family="Roboto", font_color="black"))
393
 
 
394
  analysis_text = analyze_historical_segment(df_filtered, valid_assets, period_name)
395
  formatted_analysis = f"### ๐Ÿค– AI Analyst Report: {period_name}\n\n{analysis_text}"
396
  yield fig, formatted_analysis
 
398
  except Exception as e:
399
  import traceback
400
  traceback.print_exc()
401
+ yield go.Figure(), f"### Error: {str(e)}"
402
 
403
 
404
  # =========================================
405
+ # Tab 2 Logic: Forecast & Analysis
406
  # =========================================
407
 
408
  def get_latest_data_window(window_size=30):
 
409
  print("Fetching prediction data...")
410
  lookback_days = window_size + 150
411
  end_date = datetime.now().strftime('%Y-%m-%d')
412
  start_date = (datetime.now() - timedelta(days=lookback_days)).strftime('%Y-%m-%d')
413
+ temp_filename = os.path.join(project_root, "data", "temp_gradio_prediction_data.csv")
414
  fetch_market_data(start_date, end_date, temp_filename)
415
  if not os.path.exists(temp_filename): raise Exception("Failed to fetch market data file.")
416
  df = pd.read_csv(temp_filename, index_col=0, parse_dates=True)
417
  df.dropna(inplace=True)
418
+ if len(df) < window_size: raise Exception(f"Not enough clean data fetched.")
419
  return df.iloc[-window_size:].copy()
420
 
421
  def prepare_observation(data_window):
 
424
  norm_prices = price_data / (price_data[0] + 1e-8)
425
  norm_macro = macro_data / (macro_data[0] + 1e-8)
426
  obs = np.concatenate([norm_prices, norm_macro], axis=1)
 
427
  return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
428
 
429
  def predict_and_analyze():
 
430
  status_msg = "Starting process..."
431
  loading_html = """<div style="color: #9ca3af;">๐Ÿ”„ Fetching data & running prediction...</div>"""
 
432
  yield status_msg, None, go.Figure(), loading_html
433
 
434
  try:
435
  data_window = get_latest_data_window(WINDOW_SIZE)
 
436
  flat_obs, raw_obs, df_window_for_analyst = prepare_observation(data_window)
437
 
438
  if not os.path.exists(MODEL_PATH): raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
439
  model = SAC.load(MODEL_PATH)
440
 
 
441
  status_msg = "Calculating feature importance..."
442
  yield status_msg, None, go.Figure(), loading_html
443
+ xai_plot = calculate_feature_importance(model, flat_obs)
444
 
 
445
  action, _ = model.predict(flat_obs, deterministic=True)
446
  exp_action = np.exp(np.asarray(action).flatten())
447
  weights = exp_action / np.sum(exp_action)
 
452
 
453
  status_msg = "Prediction done. Running AI Risk Analysis..."
454
  analysing_html = """<div style="color: #9ca3af;">๐Ÿค– Running Qwen-2.5-3B Risk Analysis...</div>"""
 
455
  yield status_msg, alloc_df, xai_plot, analysing_html
456
 
457
  allocations_for_llm = {k: float(v) for k, v in allocations_dict.items()}
 
463
  risk = analysis_result.get('risk_level', 'N/A').upper()
464
  just = analysis_result.get('justification', 'N/A')
465
  conf = analysis_result.get('confidence_score', 'N/A')
466
+
467
+ risk_css = "color: #ef4444;" if 'HIGH' in risk else "color: #10b981;"
468
+ status_bg = "#7f1d1d" if 'HIGH' in risk else "#064e3b"
469
+ status_border = "#ef4444" if 'HIGH' in risk else "#10b981"
470
+ status_icon = "โ›”" if 'HIGH' in risk else "๐Ÿš€"
471
+ status_text = "TRADE BLOCKED: High Risk Detected" if 'HIGH' in risk else "TRADE APPROVED"
 
 
 
 
 
 
472
 
473
  report_html = f"""
474
  <div style="background-color: #1f2937; padding: 20px; border-radius: 12px 12px 0 0; border: 1px solid #374151; border-bottom: none;">
 
483
  </div>"""
484
  else:
485
  report_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Analysis Failed to Parse</h3><p>{str(analysis_result)}</p></div>"""
486
+
487
  yield status_msg, alloc_df, xai_plot, report_html
488
  except Exception as e:
489
  import traceback
490
  traceback.print_exc()
491
+ yield status_msg, None, go.Figure(), f"Error: {str(e)}"
 
 
 
 
492
 
493
  # =========================================
494
  # Tab 1 Logic: Live Dashboard (DUMMY DATA)
495
  # =========================================
496
  def get_dashboard_metrics():
497
  return "$135,400", "+3.07%"
 
498
  def get_portfolio_history_plot():
499
  dates = pd.date_range(start="2023-01-01", periods=100)
500
  np.random.seed(42)
501
+ rl_value = 10000 * np.cumprod(1 + np.random.normal(0.001, 0.01, 100))
502
+ bnh_value = 10000 * np.cumprod(1 + np.random.normal(0.0005, 0.012, 100))
 
 
503
  fig = go.Figure()
504
+ fig.add_trace(go.Scatter(x=dates, y=rl_value, mode='lines', name='RL Agent', line=dict(color='#10b981', width=3)))
505
  fig.add_trace(go.Scatter(x=dates, y=bnh_value, mode='lines', name='Benchmark', line=dict(color='#6b7280', dash='dash')))
506
+ fig.update_layout(title="Portfolio Net Worth (Live)", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
507
  return fig
 
508
  def get_current_allocation_plot():
509
+ fig = px.pie(values=[0.25, 0.1, 0.3, 0.15, 0.05, 0.15], names=ASSETS+['Cash'], title="Holdings", color_discrete_sequence=px.colors.qualitative.Bold)
510
+ fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
 
 
 
511
  return fig
 
512
  def get_recent_transactions():
513
+ return pd.DataFrame([["2025-11-24", "SELL", "SPY", "$4,500"], ["2025-11-21", "BUY", "BTC-USD", "$1,000"]], columns=["Date", "Type", "Asset", "Value"])
 
 
514
 
515
  # =========================================
516
  # Gradio Interface
517
  # =========================================
 
518
  custom_css = """
519
  .metric-box { background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151; text-align: center; }
520
  .metric-label { font-size: 1.1em; color: #9ca3af; margin-bottom: 5px; }
 
522
  .disclaimer-box { background-color: #374151; padding: 15px; border-radius: 8px; border-left: 4px solid #f59e0b; color: #d1d5db; font-size: 0.9em; margin-bottom: 20px; }
523
  """
524
 
525
+ # Using theme=gr.themes.Soft(...) here because we forced requirements to support it
526
+ with gr.Blocks(css=custom_css, title="Deep RL Manager") as demo:
527
+ gr.HTML("""<script>function f(){document.body.classList.add('dark');} f(); setTimeout(f, 500);</script>""")
 
 
 
 
 
 
 
528
  gr.Markdown("# ๐Ÿง  Deep RL & LLM Portfolio Manager")
529
 
530
  with gr.Tabs():
531
+ with gr.TabItem("๐Ÿ“Š Dashboard"):
532
+ nw, ch = get_dashboard_metrics()
 
533
  with gr.Row():
534
+ gr.HTML(f"<div class='metric-box'><div>Net Worth</div><div class='metric-value'>{nw}</div></div>")
535
+ gr.HTML(f"<div class='metric-box'><div>Change</div><div class='metric-value' style='color:#10b981'>{ch}</div></div>")
 
 
 
 
 
 
536
  with gr.Row():
537
+ with gr.Column(scale=3): gr.Plot(value=get_portfolio_history_plot())
538
+ with gr.Column(scale=1): gr.Plot(value=get_current_allocation_plot())
 
 
539
  with gr.Row():
540
+ with gr.Column(): gr.Dataframe(value=get_recent_transactions(), label="Transactions")
541
+
542
+ with gr.TabItem("๐Ÿ”ฎ Forecast"):
543
+ btn = gr.Button("๐Ÿš€ Run Analysis", variant="primary")
544
+ stat = gr.Textbox(label="Status", interactive=False)
 
 
 
 
 
 
 
 
545
  with gr.Row():
 
546
  with gr.Column(scale=2):
547
+ alloc = gr.Dataframe(label="Allocation")
548
+ xai = gr.Plot(label="XAI")
 
 
 
 
 
 
549
  with gr.Column(scale=3):
550
+ rep = gr.HTML(label="Report")
551
+ btn.click(predict_and_analyze, None, [stat, alloc, xai, rep])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
552
 
553
+ with gr.TabItem("๐Ÿ“… Analyst"):
554
  with gr.Row():
555
  with gr.Column(scale=1):
556
+ ticks = ASSETS + FRED_IDS.values() if DASHBOARD_DATA_DF is None else [c for c in ASSETS + list(FRED_IDS.values()) if c in DASHBOARD_DATA_DF.columns]
557
+ sel = gr.Dropdown(choices=ticks, multiselect=True, label="Assets")
558
+ per = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="Period")
559
+ btn = gr.Button("Analyze", variant="primary")
 
560
  with gr.Column(scale=3):
561
+ plot = gr.Plot()
562
+ out = gr.Markdown()
563
+ btn.click(run_historical_analysis, [sel, per], [plot, out])
564
 
565
+ with gr.TabItem("๐Ÿ”™ Simulation"):
566
+ with gr.Row():
567
+ s_d = gr.Textbox(label="Start", value="2024-01-01")
568
+ e_d = gr.Textbox(label="End", value="2025-01-01")
569
+ btn = gr.Button("Run", variant="primary")
570
+ stat = gr.Textbox(label="Status")
571
+ plot = gr.Plot()
572
+ met = gr.Dataframe(label="Metrics")
573
+ btn.click(run_historical_simulation, [s_d, e_d], [plot, stat, met])
574
 
575
  if __name__ == "__main__":
576
  demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, share=True)