Update scripts/app.py
Browse files- scripts/app.py +216 -496
scripts/app.py
CHANGED
|
@@ -10,395 +10,232 @@ import os
|
|
| 10 |
import sys
|
| 11 |
import json
|
| 12 |
import torch
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|
| 27 |
TRAIN_END_DATE = "2023-01-01"
|
| 28 |
-
|
| 29 |
-
# Global variable for dashboard data needed for Tabs 3 & 4
|
| 30 |
DASHBOARD_DATA_DF = None
|
| 31 |
|
| 32 |
-
# Define Time Period mappings for the dropdown
|
| 33 |
TIME_PERIODS = {
|
| 34 |
-
"6 Months": 180,
|
| 35 |
-
"
|
| 36 |
-
"2 Years": 730,
|
| 37 |
-
"5 Years": 1825,
|
| 38 |
-
"Max Available": 9999 # Sentinel value for max
|
| 39 |
}
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
# Initialization Functions
|
| 43 |
-
# =========================================
|
| 44 |
-
|
| 45 |
def initialize_dashboard_data():
|
| 46 |
-
"""Fetches and loads historical data at startup for Tabs 3 & 4."""
|
| 47 |
global DASHBOARD_DATA_DF
|
| 48 |
-
print("--- Initializing
|
| 49 |
-
|
| 50 |
-
# Fetching last 6 years to support longer analysis periods and simulation
|
| 51 |
end_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
| 52 |
start_date = (datetime.now() - timedelta(days=365*6)).strftime('%Y-%m-%d')
|
| 53 |
|
| 54 |
-
|
| 55 |
-
# This might take a minute on first run
|
| 56 |
fetch_market_data(start_date, end_date, DASHBOARD_DATA_PATH)
|
| 57 |
|
| 58 |
if os.path.exists(DASHBOARD_DATA_PATH):
|
| 59 |
DASHBOARD_DATA_DF = pd.read_csv(DASHBOARD_DATA_PATH, index_col=0, parse_dates=True)
|
| 60 |
-
# Basic cleaning
|
| 61 |
DASHBOARD_DATA_DF.dropna(how='all', inplace=True)
|
| 62 |
-
# Calculate equal weight return for dashboard metrics
|
| 63 |
asset_cols = [c for c in ASSETS if c in DASHBOARD_DATA_DF.columns]
|
| 64 |
if asset_cols:
|
| 65 |
DASHBOARD_DATA_DF['Daily_Ret_Eq'] = DASHBOARD_DATA_DF[asset_cols].pct_change().mean(axis=1)
|
| 66 |
-
print(f"Data loaded
|
| 67 |
-
print(f"Data range: {DASHBOARD_DATA_DF.index.min().date()} to {DASHBOARD_DATA_DF.index.max().date()}")
|
| 68 |
else:
|
| 69 |
-
print("โ Failed to initialize
|
| 70 |
|
| 71 |
-
# Initialize data at startup
|
| 72 |
try:
|
|
|
|
| 73 |
initialize_dashboard_data()
|
| 74 |
except Exception as e:
|
| 75 |
-
print(f"Warning:
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# =========================================
|
| 79 |
-
# Professional Metrics & Evaluation Functions
|
| 80 |
-
# =========================================
|
| 81 |
|
|
|
|
| 82 |
def evaluate_agent_pro(env, model):
|
| 83 |
-
"""
|
| 84 |
-
Runs the trained agent on the environment and returns portfolio values.
|
| 85 |
-
"""
|
| 86 |
obs, info = env.reset()
|
| 87 |
terminated, truncated = False, False
|
| 88 |
-
portfolio_values = [env.
|
| 89 |
-
|
| 90 |
while not (terminated or truncated):
|
| 91 |
action, _states = model.predict(obs, deterministic=True)
|
| 92 |
obs, reward, terminated, truncated, info = env.step(action)
|
| 93 |
portfolio_values.append(info['portfolio_value'])
|
| 94 |
-
|
| 95 |
-
# Align index with the actual steps taken
|
| 96 |
valid_dates = env.df.index[env.window_size-1:]
|
| 97 |
return pd.Series(portfolio_values, index=valid_dates[:len(portfolio_values)])
|
| 98 |
|
| 99 |
def calculate_metrics_pro(portfolio_values, freq=252, rf=0.0):
|
| 100 |
-
"""
|
| 101 |
-
Calculates key professional performance metrics from a series of portfolio values.
|
| 102 |
-
"""
|
| 103 |
-
if len(portfolio_values) < 2:
|
| 104 |
-
return {k: "N/A" for k in ["Total Return", "CAGR", "Sharpe Ratio", "Sortino Ratio", "Volatility", "Max Drawdown", "Calmar Ratio"]}
|
| 105 |
-
|
| 106 |
returns = portfolio_values.pct_change().dropna()
|
| 107 |
-
if returns.empty:
|
| 108 |
-
return {k: "0.00%" if "%" in k else "0.00" for k in ["Total Return", "CAGR", "Sharpe Ratio", "Sortino Ratio", "Volatility", "Max Drawdown", "Calmar Ratio"]}
|
| 109 |
|
| 110 |
total_return = (portfolio_values.iloc[-1] / portfolio_values.iloc[0]) - 1
|
| 111 |
num_years = (len(portfolio_values) - 1) / freq
|
| 112 |
cagr = (portfolio_values.iloc[-1] / portfolio_values.iloc[0]) ** (1/num_years) - 1 if num_years > 0 else 0.0
|
| 113 |
-
|
| 114 |
-
sharpe_ratio = np.sqrt(freq) * (returns.mean() - rf) / returns.std() if returns.std() > 0 else np.nan
|
| 115 |
-
|
| 116 |
downside_returns = returns[returns < 0]
|
| 117 |
-
|
| 118 |
-
sortino_ratio = np.sqrt(freq) * (returns.mean() - rf) / downside_std if downside_std > 0 else np.nan
|
| 119 |
-
|
| 120 |
volatility = returns.std() * np.sqrt(freq)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
max_drawdown = drawdown.min()
|
| 125 |
-
|
| 126 |
-
calmar_ratio = cagr / abs(max_drawdown) if max_drawdown != 0 and cagr != 0 else np.nan
|
| 127 |
|
| 128 |
return {
|
| 129 |
-
"Total Return": total_return,
|
| 130 |
-
"
|
| 131 |
-
"Sharpe Ratio": sharpe_ratio,
|
| 132 |
-
"Sortino Ratio": sortino_ratio,
|
| 133 |
-
"Volatility": volatility,
|
| 134 |
-
"Max Drawdown": max_drawdown,
|
| 135 |
"Calmar Ratio": calmar_ratio
|
| 136 |
}
|
| 137 |
|
| 138 |
-
# =========================================
|
| 139 |
-
# XAI: Feature Importance Function
|
| 140 |
-
# =========================================
|
| 141 |
def calculate_feature_importance(model, obs):
|
| 142 |
-
"""
|
| 143 |
-
Calculates feature importance using Integrated Gradients on the RL agent's policy network.
|
| 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)
|
| 150 |
actor = model.policy.actor
|
| 151 |
-
|
| 152 |
-
# Define a baseline (e.g., a zero observation)
|
| 153 |
baseline = torch.zeros_like(obs_tensor)
|
| 154 |
-
|
| 155 |
-
# Number of steps for integral approximation
|
| 156 |
steps = 50
|
| 157 |
-
|
| 158 |
-
# Generate scaled inputs along the path from baseline to input
|
| 159 |
scaled_inputs = [baseline + (float(i) / steps) * (obs_tensor - baseline) for i in range(steps + 1)]
|
| 160 |
|
| 161 |
grads = []
|
| 162 |
for scaled_input in scaled_inputs:
|
| 163 |
-
# Forward pass to get action distribution parameters (mean)
|
| 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 |
-
#
|
| 175 |
-
|
| 176 |
-
avg_grads =
|
|
|
|
|
|
|
| 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:
|
| 192 |
-
feature_names.append(f"{asset}_t-{WINDOW_SIZE-1-i}")
|
| 193 |
for i in range(WINDOW_SIZE):
|
| 194 |
-
for macro in MACRO_COLS:
|
| 195 |
-
feature_names.append(f"{macro}_t-{WINDOW_SIZE-1-i}")
|
| 196 |
|
| 197 |
-
# Combine into a dictionary and sort by absolute importance
|
| 198 |
feature_importance_dict = dict(zip(feature_names, importance_scores))
|
| 199 |
-
|
| 200 |
-
# Aggregate importance by feature type (sum of absolute values across time steps)
|
| 201 |
aggregated_importance = {}
|
| 202 |
for base_feature in ASSETS + MACRO_COLS:
|
| 203 |
total_imp = sum(abs(val) for key, val in feature_importance_dict.items() if key.startswith(base_feature))
|
| 204 |
aggregated_importance[base_feature] = total_imp
|
| 205 |
|
| 206 |
-
# Sort and take top N for display
|
| 207 |
top_features = dict(sorted(aggregated_importance.items(), key=lambda item: item[1], reverse=True)[:8])
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
labels={'x': 'Relative Importance Score', 'y': 'Feature'},
|
| 216 |
-
color=list(top_features.values()),
|
| 217 |
-
color_continuous_scale=px.colors.sequential.Viridis
|
| 218 |
-
)
|
| 219 |
-
fig.update_layout(
|
| 220 |
-
template="plotly_dark",
|
| 221 |
-
paper_bgcolor='rgba(0,0,0,0)',
|
| 222 |
-
plot_bgcolor='rgba(0,0,0,0)',
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 256 |
-
|
| 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 |
-
|
| 264 |
-
|
| 265 |
-
|
| 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=
|
| 298 |
-
fig.add_trace(go.Scatter(x=
|
| 299 |
-
fig.add_trace(go.Scatter(x=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 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}"
|
| 321 |
-
|
| 322 |
-
metrics_data = {
|
| 323 |
-
"Metric": ["Total Return", "CAGR", "Sharpe Ratio", "Sortino Ratio", "Volatility (Ann.)", "Max Drawdown", "Calmar Ratio"],
|
| 324 |
-
"RL Agent (SAC)": [fmt(rl_m["Total Return"]), fmt(rl_m["CAGR"]), fmt(rl_m["Sharpe Ratio"], False), fmt(rl_m["Sortino Ratio"], False), fmt(rl_m["Volatility"]), fmt(rl_m["Max Drawdown"]), fmt(rl_m["Calmar Ratio"], False)],
|
| 325 |
-
"Buy & Hold (SPY)": [fmt(bnh_m["Total Return"]), fmt(bnh_m["CAGR"]), fmt(bnh_m["Sharpe Ratio"], False), fmt(bnh_m["Sortino Ratio"], False), fmt(bnh_m["Volatility"]), fmt(bnh_m["Max Drawdown"]), fmt(bnh_m["Calmar Ratio"], False)],
|
| 326 |
-
"Equal Weighted": [fmt(eq_m["Total Return"]), fmt(eq_m["CAGR"]), fmt(eq_m["Sharpe Ratio"], False), fmt(eq_m["Sortino Ratio"], False), fmt(eq_m["Volatility"]), fmt(eq_m["Max Drawdown"]), fmt(eq_m["Calmar Ratio"], False)],
|
| 327 |
}
|
| 328 |
-
|
| 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 |
-
|
| 338 |
-
traceback.print_exc()
|
| 339 |
-
yield go.Figure(), f"Error during simulation: {str(e)}", gr.update(visible=False)
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
# =========================================
|
| 343 |
-
# Tab 3 Logic: Historical Data Analyst
|
| 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 |
-
|
| 351 |
-
status_html = """<div style="color: #9ca3af;">๐ Processing data and running AI analysis...</div>"""
|
| 352 |
-
yield go.Figure(), status_html
|
| 353 |
|
|
|
|
|
|
|
|
|
|
| 354 |
try:
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 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 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
| 380 |
except Exception as e:
|
| 381 |
-
|
| 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 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
fetch_market_data(
|
| 398 |
-
if not os.path.exists(
|
| 399 |
-
df = pd.read_csv(
|
| 400 |
df.dropna(inplace=True)
|
| 401 |
-
if len(df) < window_size: raise Exception(
|
| 402 |
return df.iloc[-window_size:].copy()
|
| 403 |
|
| 404 |
def prepare_observation(data_window):
|
|
@@ -407,258 +244,141 @@ 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
|
|
|
|
| 411 |
return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
|
| 412 |
|
| 413 |
def predict_and_analyze():
|
| 414 |
-
""
|
| 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 =
|
| 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(
|
| 426 |
model = SAC.load(MODEL_PATH)
|
| 427 |
|
| 428 |
-
# ---
|
| 429 |
-
|
| 430 |
-
yield
|
| 431 |
-
xai_plot = calculate_feature_importance(model,
|
| 432 |
|
| 433 |
-
# --- Prediction ---
|
| 434 |
action, _ = model.predict(flat_obs, deterministic=True)
|
| 435 |
-
|
| 436 |
-
weights =
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
alloc_df
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 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;">
|
| 471 |
-
<h3 style="margin-top: 0; color: #e5e7eb;">๐ค AI Risk Analyst Report</h3>
|
| 472 |
-
<div style="margin-bottom: 15px;"><strong style="color: #9ca3af;">Strategy:</strong><br><span style="color: #d1d5db;">{strat}</span></div>
|
| 473 |
-
<div style="margin-bottom: 15px;"><strong style="color: #9ca3af;">Risk Level:</strong><span style="margin-left: 8px; {risk_css}">{risk}</span></div>
|
| 474 |
-
<div style="margin-bottom: 15px;"><strong style="color: #9ca3af;">Justification:</strong><br><span style="color: #d1d5db;">{just}</span></div>
|
| 475 |
-
<div><strong style="color: #9ca3af;">Confidence:</strong> <span style="color: #d1d5db;">{conf}/10</span></div>
|
| 476 |
-
</div>
|
| 477 |
-
<div style="background-color: {status_bg}; color: white; padding: 15px; border-radius: 0 0 12px 12px; border: 2px solid {status_border}; text-align: center; font-size: 1.2em; font-weight: bold; display: flex; align-items: center; justify-content: center;">
|
| 478 |
-
<span style="margin-right: 10px; font-size: 1.4em;">{status_icon}</span>{status_text}
|
| 479 |
-
</div>"""
|
| 480 |
else:
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
yield
|
| 484 |
except Exception as e:
|
| 485 |
import traceback
|
| 486 |
traceback.print_exc()
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
#
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
dates =
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 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
|
| 513 |
-
|
| 514 |
-
|
| 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
|
| 521 |
-
|
| 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;
|
| 532 |
.metric-value { font-size: 2.2em; font-weight: 700; color: #e5e7eb; }
|
| 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
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
with gr.Blocks(
|
| 541 |
-
# theme=theme, css=custom_css,
|
| 542 |
-
title="Deep RL Portfolio Manager") as demo:
|
| 543 |
-
gr.HTML("""<script>function forceDark(){document.body.classList.add('dark');} forceDark(); setTimeout(forceDark, 500);</script>""")
|
| 544 |
-
|
| 545 |
gr.Markdown("# ๐ง Deep RL & LLM Portfolio Manager")
|
| 546 |
|
| 547 |
with gr.Tabs():
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
# Metrics Row
|
| 551 |
with gr.Row():
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
with gr.Column(elem_classes=["metric-box"]):
|
| 555 |
-
gr.HTML(f"<div class='metric-label'>Current Net Worth</div><div class='metric-value'>{nw_val}</div>")
|
| 556 |
-
with gr.Column(elem_classes=["metric-box"]):
|
| 557 |
-
gr.HTML(f"<div class='metric-label'>24h Change</div><div class='metric-value' style='color: #10b981;'>{dc_val}</div>")
|
| 558 |
-
|
| 559 |
-
# Main Chart row
|
| 560 |
with gr.Row():
|
| 561 |
-
with gr.Column(scale=3):
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
# Bottom Row: Allocations and Transactions
|
| 565 |
with gr.Row():
|
| 566 |
-
with gr.Column(
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
# ================= TAB 2: FORECAST (UPDATED with XAI) =================
|
| 573 |
-
with gr.TabItem("๐ฎ Forecast & AI Analysis"):
|
| 574 |
-
gr.Markdown("### Generate Tomorrow's Portfolio Strategy")
|
| 575 |
-
run_btn = gr.Button("๐ Run Overnight Analysis", variant="primary", size="lg")
|
| 576 |
-
status_output = gr.Textbox(label="System Status", placeholder="Ready...", interactive=False, lines=1)
|
| 577 |
-
gr.Markdown("---")
|
| 578 |
-
|
| 579 |
with gr.Row():
|
| 580 |
-
# Left Column: Allocations & XAI Plot
|
| 581 |
with gr.Column(scale=2):
|
| 582 |
-
gr.
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
# NEW: XAI Feature Importance Plot
|
| 586 |
-
gr.Markdown("### ๐ง Why did the agent choose this?")
|
| 587 |
-
xai_output_plot = gr.Plot(label="Top Influential Factors (XAI)", show_label=False)
|
| 588 |
-
|
| 589 |
-
# Right Column: AI Analysis Report
|
| 590 |
with gr.Column(scale=3):
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
# Updated click event with new XAI output
|
| 594 |
-
run_btn.click(
|
| 595 |
-
fn=predict_and_analyze,
|
| 596 |
-
inputs=None,
|
| 597 |
-
outputs=[status_output, allocation_output, xai_output_plot, analysis_report_html]
|
| 598 |
-
)
|
| 599 |
-
|
| 600 |
-
# ================= TAB 3: HISTORICAL DATA ANALYST =================
|
| 601 |
-
with gr.TabItem("๐
Historical Data Analyst"):
|
| 602 |
-
gr.Markdown("### Analyze Past Market Performance with AI")
|
| 603 |
-
|
| 604 |
-
with gr.Row():
|
| 605 |
-
with gr.Column(scale=1):
|
| 606 |
-
all_tickers_hist = ASSETS + list(FRED_IDS.values())
|
| 607 |
-
if DASHBOARD_DATA_DF is not None:
|
| 608 |
-
available_tickers_hist = [t for t in all_tickers_hist if t in DASHBOARD_DATA_DF.columns]
|
| 609 |
-
else:
|
| 610 |
-
available_tickers_hist = []
|
| 611 |
-
default_tickers_hist = available_tickers_hist[:3] if available_tickers_hist else []
|
| 612 |
-
|
| 613 |
-
asset_selector = gr.Dropdown(choices=available_tickers_hist, value=default_tickers_hist, multiselect=True, label="1. Select Assets")
|
| 614 |
-
period_selector = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="2. Select Period")
|
| 615 |
-
analyze_btn = gr.Button("๐ Run Analysis", variant="primary")
|
| 616 |
-
|
| 617 |
-
with gr.Column(scale=3):
|
| 618 |
-
historical_plot = gr.Plot(label="Performance Plot")
|
| 619 |
-
|
| 620 |
-
gr.Markdown("---")
|
| 621 |
-
historical_analysis_md = gr.Markdown("### ๐ค AI Analyst Report\n\n*Click 'Run Analysis' to generate.*")
|
| 622 |
-
|
| 623 |
-
analyze_btn.click(
|
| 624 |
-
fn=run_historical_analysis,
|
| 625 |
-
inputs=[asset_selector, period_selector],
|
| 626 |
-
outputs=[historical_plot, historical_analysis_md]
|
| 627 |
-
)
|
| 628 |
-
|
| 629 |
-
# ================= TAB 4: HISTORICAL SIMULATION (UPDATED with Pro Metrics) =================
|
| 630 |
-
with gr.TabItem("๐ Historical Simulation"):
|
| 631 |
-
gr.Markdown("### Backtest the RL Agent against Baselines")
|
| 632 |
-
|
| 633 |
-
# Disclaimer Box
|
| 634 |
-
gr.HTML(f"""
|
| 635 |
-
<div class='disclaimer-box'>
|
| 636 |
-
<strong>โ ๏ธ IMPORTANT DISCLAIMER:</strong> The RL model was trained on data from approximately
|
| 637 |
-
<strong>{TRAIN_START_DATE} to {TRAIN_END_DATE}</strong>. Running simulations outside or overlapping significantly
|
| 638 |
-
with this period may not accurately reflect real-world performance (lookahead bias or out-of-distribution data).
|
| 639 |
-
Use for educational purposes only.
|
| 640 |
-
</div>
|
| 641 |
-
""")
|
| 642 |
|
|
|
|
| 643 |
with gr.Row():
|
| 644 |
with gr.Column(scale=1):
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
with gr.Column(scale=3):
|
| 651 |
-
|
|
|
|
|
|
|
| 652 |
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
)
|
| 662 |
|
| 663 |
if __name__ == "__main__":
|
| 664 |
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: sys.path.insert(0, project_root)
|
| 29 |
+
except NameError:
|
| 30 |
+
project_root = os.getcwd()
|
| 31 |
+
if project_root not in sys.path: sys.path.insert(0, project_root)
|
| 32 |
+
|
| 33 |
+
print(f"Project Root set to: {project_root}")
|
| 34 |
+
|
| 35 |
+
# --- Imports ---
|
| 36 |
+
from scripts.fetch_market_data import fetch_market_data, ASSETS, FRED_IDS
|
| 37 |
+
from scripts.llm_analysis_rag import analyze_agent_decision, analyze_historical_segment, setup_rag_chain, query_rag_chain
|
| 38 |
from stable_baselines3 import SAC
|
| 39 |
+
from scripts.environment import PortfolioEnv
|
| 40 |
from scripts.evaluate_baselines import buy_and_hold, equally_weighted_rebalanced
|
| 41 |
|
| 42 |
# --- Configuration ---
|
| 43 |
+
MODEL_PATH = os.path.join(project_root, "checkpoints", "sac_portfolio_model.zip")
|
| 44 |
WINDOW_SIZE = 30
|
| 45 |
MACRO_COLS = list(FRED_IDS.values())
|
| 46 |
+
DASHBOARD_DATA_PATH = os.path.join(project_root, "data", "historical_dashboard_data.csv")
|
|
|
|
|
|
|
| 47 |
TRAIN_START_DATE = "2015-01-01"
|
| 48 |
TRAIN_END_DATE = "2023-01-01"
|
|
|
|
|
|
|
| 49 |
DASHBOARD_DATA_DF = None
|
| 50 |
|
|
|
|
| 51 |
TIME_PERIODS = {
|
| 52 |
+
"6 Months": 180, "1 Year": 365, "2 Years": 730,
|
| 53 |
+
"5 Years": 1825, "Max Available": 9999
|
|
|
|
|
|
|
|
|
|
| 54 |
}
|
| 55 |
|
| 56 |
+
# --- Initialization ---
|
|
|
|
|
|
|
|
|
|
| 57 |
def initialize_dashboard_data():
|
|
|
|
| 58 |
global DASHBOARD_DATA_DF
|
| 59 |
+
print("--- Initializing Data ---")
|
|
|
|
|
|
|
| 60 |
end_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
| 61 |
start_date = (datetime.now() - timedelta(days=365*6)).strftime('%Y-%m-%d')
|
| 62 |
|
| 63 |
+
os.makedirs(os.path.dirname(DASHBOARD_DATA_PATH), exist_ok=True)
|
|
|
|
| 64 |
fetch_market_data(start_date, end_date, DASHBOARD_DATA_PATH)
|
| 65 |
|
| 66 |
if os.path.exists(DASHBOARD_DATA_PATH):
|
| 67 |
DASHBOARD_DATA_DF = pd.read_csv(DASHBOARD_DATA_PATH, index_col=0, parse_dates=True)
|
|
|
|
| 68 |
DASHBOARD_DATA_DF.dropna(how='all', inplace=True)
|
|
|
|
| 69 |
asset_cols = [c for c in ASSETS if c in DASHBOARD_DATA_DF.columns]
|
| 70 |
if asset_cols:
|
| 71 |
DASHBOARD_DATA_DF['Daily_Ret_Eq'] = DASHBOARD_DATA_DF[asset_cols].pct_change().mean(axis=1)
|
| 72 |
+
print(f"Data loaded. Shape: {DASHBOARD_DATA_DF.shape}")
|
|
|
|
| 73 |
else:
|
| 74 |
+
print("โ Failed to initialize data.")
|
| 75 |
|
|
|
|
| 76 |
try:
|
| 77 |
+
setup_rag_chain()
|
| 78 |
initialize_dashboard_data()
|
| 79 |
except Exception as e:
|
| 80 |
+
print(f"Init Warning: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# --- Helper Functions ---
|
| 83 |
def evaluate_agent_pro(env, model):
|
|
|
|
|
|
|
|
|
|
| 84 |
obs, info = env.reset()
|
| 85 |
terminated, truncated = False, False
|
| 86 |
+
portfolio_values = [env.initial_balance]
|
|
|
|
| 87 |
while not (terminated or truncated):
|
| 88 |
action, _states = model.predict(obs, deterministic=True)
|
| 89 |
obs, reward, terminated, truncated, info = env.step(action)
|
| 90 |
portfolio_values.append(info['portfolio_value'])
|
|
|
|
|
|
|
| 91 |
valid_dates = env.df.index[env.window_size-1:]
|
| 92 |
return pd.Series(portfolio_values, index=valid_dates[:len(portfolio_values)])
|
| 93 |
|
| 94 |
def calculate_metrics_pro(portfolio_values, freq=252, rf=0.0):
|
| 95 |
+
if len(portfolio_values) < 2: return {k: "N/A" for k in ["Total Return", "CAGR", "Sharpe Ratio", "Sortino Ratio", "Volatility", "Max Drawdown", "Calmar Ratio"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
returns = portfolio_values.pct_change().dropna()
|
| 97 |
+
if returns.empty: return {k: "0.00" for k in ["Total Return", "CAGR", "Sharpe Ratio", "Sortino Ratio", "Volatility", "Max Drawdown", "Calmar Ratio"]}
|
|
|
|
| 98 |
|
| 99 |
total_return = (portfolio_values.iloc[-1] / portfolio_values.iloc[0]) - 1
|
| 100 |
num_years = (len(portfolio_values) - 1) / freq
|
| 101 |
cagr = (portfolio_values.iloc[-1] / portfolio_values.iloc[0]) ** (1/num_years) - 1 if num_years > 0 else 0.0
|
| 102 |
+
sharpe_ratio = np.sqrt(freq) * (returns.mean() - rf) / returns.std() if returns.std() > 0 else 0
|
|
|
|
|
|
|
| 103 |
downside_returns = returns[returns < 0]
|
| 104 |
+
sortino_ratio = np.sqrt(freq) * (returns.mean() - rf) / downside_returns.std() if downside_returns.std() > 0 else 0
|
|
|
|
|
|
|
| 105 |
volatility = returns.std() * np.sqrt(freq)
|
| 106 |
+
peak = portfolio_values.cummax()
|
| 107 |
+
max_drawdown = ((portfolio_values - peak) / peak).min()
|
| 108 |
+
calmar_ratio = cagr / abs(max_drawdown) if max_drawdown != 0 else 0
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
return {
|
| 111 |
+
"Total Return": total_return, "CAGR": cagr, "Sharpe Ratio": sharpe_ratio,
|
| 112 |
+
"Sortino Ratio": sortino_ratio, "Volatility": volatility, "Max Drawdown": max_drawdown,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
"Calmar Ratio": calmar_ratio
|
| 114 |
}
|
| 115 |
|
|
|
|
|
|
|
|
|
|
| 116 |
def calculate_feature_importance(model, obs):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
obs_tensor = torch.as_tensor(obs, dtype=torch.float32, device=model.device)
|
| 118 |
+
if obs_tensor.dim() == 1: obs_tensor = obs_tensor.unsqueeze(0)
|
| 119 |
obs_tensor.requires_grad_()
|
| 120 |
+
|
|
|
|
| 121 |
actor = model.policy.actor
|
|
|
|
|
|
|
| 122 |
baseline = torch.zeros_like(obs_tensor)
|
|
|
|
|
|
|
| 123 |
steps = 50
|
|
|
|
|
|
|
| 124 |
scaled_inputs = [baseline + (float(i) / steps) * (obs_tensor - baseline) for i in range(steps + 1)]
|
| 125 |
|
| 126 |
grads = []
|
| 127 |
for scaled_input in scaled_inputs:
|
|
|
|
| 128 |
action_mean = actor(scaled_input)
|
|
|
|
|
|
|
|
|
|
| 129 |
target_output = action_mean.sum()
|
|
|
|
|
|
|
| 130 |
grad = torch.autograd.grad(outputs=target_output, inputs=scaled_input)[0]
|
| 131 |
grads.append(grad)
|
| 132 |
|
| 133 |
+
# --- FIX 1: Stack gradients first, then perform arithmetic ---
|
| 134 |
+
stacked_grads = torch.stack(grads)
|
| 135 |
+
avg_grads = (stacked_grads[:-1] + stacked_grads[1:]) / 2.0
|
| 136 |
+
avg_grads = avg_grads.mean(dim=0)
|
| 137 |
+
# -----------------------------------------------------------
|
| 138 |
|
|
|
|
| 139 |
integrated_grads = (obs_tensor - baseline) * avg_grads
|
|
|
|
|
|
|
| 140 |
importance_scores = integrated_grads.detach().cpu().numpy().flatten()
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
feature_names = []
|
| 143 |
for i in range(WINDOW_SIZE):
|
| 144 |
+
for asset in ASSETS: feature_names.append(f"{asset}_t-{WINDOW_SIZE-1-i}")
|
|
|
|
| 145 |
for i in range(WINDOW_SIZE):
|
| 146 |
+
for macro in MACRO_COLS: feature_names.append(f"{macro}_t-{WINDOW_SIZE-1-i}")
|
|
|
|
| 147 |
|
|
|
|
| 148 |
feature_importance_dict = dict(zip(feature_names, importance_scores))
|
|
|
|
|
|
|
| 149 |
aggregated_importance = {}
|
| 150 |
for base_feature in ASSETS + MACRO_COLS:
|
| 151 |
total_imp = sum(abs(val) for key, val in feature_importance_dict.items() if key.startswith(base_feature))
|
| 152 |
aggregated_importance[base_feature] = total_imp
|
| 153 |
|
|
|
|
| 154 |
top_features = dict(sorted(aggregated_importance.items(), key=lambda item: item[1], reverse=True)[:8])
|
| 155 |
|
| 156 |
+
fig = px.bar(x=list(top_features.values()), y=list(top_features.keys()), orientation='h',
|
| 157 |
+
title="Top Influential Features (XAI)", labels={'x': 'Importance', 'y': 'Feature'},
|
| 158 |
+
color=list(top_features.values()), color_continuous_scale=px.colors.sequential.Viridis)
|
| 159 |
+
fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
|
| 160 |
+
yaxis={'categoryorder':'total ascending'}, coloraxis_showscale=False, margin=dict(l=10, r=10, t=40, b=10), height=300,
|
| 161 |
+
hoverlabel=dict(bgcolor="white", font_size=14, font_family="Roboto", font_color="black"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
return fig
|
| 163 |
|
| 164 |
+
# --- Tab Functions ---
|
|
|
|
|
|
|
|
|
|
| 165 |
def run_historical_simulation(start_date_str, end_date_str):
|
| 166 |
+
if DASHBOARD_DATA_DF is None: return go.Figure(), "Data not initialized.", None
|
| 167 |
+
yield go.Figure(), "Preparing...", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
try:
|
| 169 |
+
start_date, end_date = pd.to_datetime(start_date_str), pd.to_datetime(end_date_str)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
if start_date < DASHBOARD_DATA_DF.index.min() or end_date > DASHBOARD_DATA_DF.index.max():
|
| 171 |
+
yield go.Figure(), "Dates out of range.", None; return
|
| 172 |
+
|
|
|
|
|
|
|
|
|
|
| 173 |
df_slice = DASHBOARD_DATA_DF.loc[start_date:end_date].copy()
|
| 174 |
asset_cols_only = [c for c in ASSETS if c in df_slice.columns]
|
| 175 |
|
| 176 |
+
yield go.Figure(), "Running RL Agent...", None
|
| 177 |
+
env = PortfolioEnv(df_slice, WINDOW_SIZE, initial_balance=10000)
|
| 178 |
+
if not os.path.exists(MODEL_PATH): raise FileNotFoundError("Model not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
model = SAC.load(MODEL_PATH)
|
| 180 |
+
rl_vals = evaluate_agent_pro(env, model)
|
| 181 |
+
|
| 182 |
+
yield go.Figure(), "Calculating baselines...", None
|
| 183 |
+
bnh_vals = buy_and_hold(df_slice[asset_cols_only], initial_balance=10000).loc[rl_vals.index[0]:]
|
| 184 |
+
bnh_vals = bnh_vals / bnh_vals.iloc[0] * 10000
|
| 185 |
+
eq_vals = equally_weighted_rebalanced(df_slice[asset_cols_only], initial_balance=10000).loc[rl_vals.index[0]:]
|
| 186 |
+
eq_vals = eq_vals / eq_vals.iloc[0] * 10000
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
fig = go.Figure()
|
| 189 |
+
fig.add_trace(go.Scatter(x=rl_vals.index, y=rl_vals, name='RL Agent (SAC)', line=dict(color='#10b981', width=3)))
|
| 190 |
+
fig.add_trace(go.Scatter(x=bnh_vals.index, y=bnh_vals, name='Buy & Hold (SPY)', line=dict(color='#6b7280', dash='dash')))
|
| 191 |
+
fig.add_trace(go.Scatter(x=eq_vals.index, y=eq_vals, name='Equal Weight', line=dict(color='#a855f7', dash='dot')))
|
| 192 |
+
fig.update_layout(title="Simulation Performance", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', hovermode="x unified",
|
| 193 |
+
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
|
| 194 |
+
|
| 195 |
+
rl_m, bnh_m, eq_m = calculate_metrics_pro(rl_vals), calculate_metrics_pro(bnh_vals), calculate_metrics_pro(eq_vals)
|
| 196 |
+
def fmt(v, p=True): return f"{v:.2%}" if p else f"{v:.2f}"
|
| 197 |
|
| 198 |
+
metrics = {
|
| 199 |
+
"Metric": ["Return", "CAGR", "Sharpe", "Sortino", "Vol", "MaxDD", "Calmar"],
|
| 200 |
+
"RL Agent": [fmt(rl_m["Total Return"]), fmt(rl_m["CAGR"]), fmt(rl_m["Sharpe Ratio"],0), fmt(rl_m["Sortino Ratio"],0), fmt(rl_m["Volatility"]), fmt(rl_m["Max Drawdown"]), fmt(rl_m["Calmar Ratio"],0)],
|
| 201 |
+
"Buy&Hold": [fmt(bnh_m["Total Return"]), fmt(bnh_m["CAGR"]), fmt(bnh_m["Sharpe Ratio"],0), fmt(bnh_m["Sortino Ratio"],0), fmt(bnh_m["Volatility"]), fmt(bnh_m["Max Drawdown"]), fmt(bnh_m["Calmar Ratio"],0)],
|
| 202 |
+
"Eq Weight": [fmt(eq_m["Total Return"]), fmt(eq_m["CAGR"]), fmt(eq_m["Sharpe Ratio"],0), fmt(eq_m["Sortino Ratio"],0), fmt(eq_m["Volatility"]), fmt(eq_m["Max Drawdown"]), fmt(eq_m["Calmar Ratio"],0)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
}
|
| 204 |
+
yield fig, "Complete", pd.DataFrame(metrics)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
except Exception as e:
|
| 206 |
+
yield go.Figure(), f"Error: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
+
def run_hist_analysis(selected_assets, period):
|
| 209 |
+
if DASHBOARD_DATA_DF is None: return go.Figure(), "No Data"
|
| 210 |
+
yield go.Figure(), "Analyzing..."
|
| 211 |
try:
|
| 212 |
+
days = TIME_PERIODS.get(period, 365)
|
| 213 |
+
start = datetime.now() - timedelta(days=days)
|
| 214 |
+
valid = [a for a in selected_assets if a in DASHBOARD_DATA_DF.columns]
|
| 215 |
+
df_sub = DASHBOARD_DATA_DF.loc[start:, valid].copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
+
if df_sub.empty: return go.Figure(), "No Data"
|
| 218 |
+
|
| 219 |
+
df_norm = df_sub / df_sub.iloc[0] * 100
|
| 220 |
+
fig = px.line(df_norm, x=df_norm.index, y=df_norm.columns, title=f"Performance {period}", color_discrete_sequence=px.colors.qualitative.Bold)
|
| 221 |
+
fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
|
| 222 |
+
|
| 223 |
+
txt = analyze_historical_segment(df_sub, valid, period)
|
| 224 |
+
yield fig, f"### ๐ค Analysis\n\n{txt}"
|
| 225 |
except Exception as e:
|
| 226 |
+
yield go.Figure(), f"Error: {e}"
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
+
def get_prediction_data(window_size=30):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
print("Fetching prediction data...")
|
| 230 |
+
lookback = window_size + 150
|
| 231 |
+
end = datetime.now().strftime('%Y-%m-%d')
|
| 232 |
+
start = (datetime.now() - timedelta(days=lookback)).strftime('%Y-%m-%d')
|
| 233 |
+
tmp_file = os.path.join(project_root, "data", "temp_pred.csv")
|
| 234 |
+
fetch_market_data(start, end, tmp_file)
|
| 235 |
+
if not os.path.exists(tmp_file): raise Exception("Fetch failed.")
|
| 236 |
+
df = pd.read_csv(tmp_file, index_col=0, parse_dates=True)
|
| 237 |
df.dropna(inplace=True)
|
| 238 |
+
if len(df) < window_size: raise Exception("Not enough data.")
|
| 239 |
return df.iloc[-window_size:].copy()
|
| 240 |
|
| 241 |
def prepare_observation(data_window):
|
|
|
|
| 244 |
norm_prices = price_data / (price_data[0] + 1e-8)
|
| 245 |
norm_macro = macro_data / (macro_data[0] + 1e-8)
|
| 246 |
obs = np.concatenate([norm_prices, norm_macro], axis=1)
|
| 247 |
+
# Return flattened obs for prediction AND flat obs for XAI calc function
|
| 248 |
+
# (Note: XAI calc func re-shapes it internally, but expects a tensor)
|
| 249 |
return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
|
| 250 |
|
| 251 |
def predict_and_analyze():
|
| 252 |
+
yield "Starting...", None, go.Figure(), "Loading..."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
try:
|
| 254 |
+
data_window = get_prediction_data(WINDOW_SIZE)
|
|
|
|
| 255 |
flat_obs, raw_obs, df_window_for_analyst = prepare_observation(data_window)
|
| 256 |
|
| 257 |
+
if not os.path.exists(MODEL_PATH): raise FileNotFoundError("Model not found.")
|
| 258 |
model = SAC.load(MODEL_PATH)
|
| 259 |
|
| 260 |
+
# --- FIX 2: Pass the FLATTENED observation to XAI function ---
|
| 261 |
+
# The XAI function logic expects an input that matches the model's input layer.
|
| 262 |
+
yield "XAI Calc...", None, go.Figure(), "Calculating XAI..."
|
| 263 |
+
xai_plot = calculate_feature_importance(model, flat_obs)
|
| 264 |
|
|
|
|
| 265 |
action, _ = model.predict(flat_obs, deterministic=True)
|
| 266 |
+
exp_act = np.exp(np.asarray(action).flatten())
|
| 267 |
+
weights = exp_act / np.sum(exp_act)
|
| 268 |
+
|
| 269 |
+
allocs = {ASSETS[i]: weights[i] for i in range(len(ASSETS))}
|
| 270 |
+
allocs['Cash'] = weights[-1]
|
| 271 |
+
alloc_df = pd.DataFrame(list(allocs.items()), columns=['Asset', 'Alloc'])
|
| 272 |
+
alloc_df['Alloc'] = alloc_df['Alloc'].apply(lambda x: f"{x:.2%}")
|
| 273 |
+
|
| 274 |
+
yield "AI Analysis...", alloc_df, xai_plot, "Running AI..."
|
| 275 |
+
llm_allocs = {k: float(v) for k, v in allocs.items()}
|
| 276 |
+
res = analyze_agent_decision(df_window_for_analyst, llm_allocs)
|
| 277 |
+
|
| 278 |
+
if isinstance(res, dict):
|
| 279 |
+
strat, risk, just, conf = res.get('strategy_summary','N/A'), res.get('risk_level','N/A').upper(), res.get('justification','N/A'), res.get('confidence_score','N/A')
|
| 280 |
+
border_col = "#ef4444" if 'HIGH' in risk else "#10b981"
|
| 281 |
+
bg_col = "#7f1d1d" if 'HIGH' in risk else "#064e3b"
|
| 282 |
+
icon = "โ" if 'HIGH' in risk else "๐"
|
| 283 |
+
status = "TRADE BLOCKED" if 'HIGH' in risk else "TRADE APPROVED"
|
| 284 |
+
|
| 285 |
+
html = f"""<div style="background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151;">
|
| 286 |
+
<h3 style="margin-top: 0; color: #e5e7eb;">๐ค AI Report</h3>
|
| 287 |
+
<p><strong>Strategy:</strong> <span style="color:#d1d5db">{strat}</span></p>
|
| 288 |
+
<p><strong>Risk:</strong> <span style="color:{border_col}; font-weight:bold">{risk}</span></p>
|
| 289 |
+
<p><strong>Reason:</strong> <span style="color:#d1d5db">{just}</span></p>
|
| 290 |
+
<p><strong>Conf:</strong> <span style="color:#d1d5db">{conf}/10</span></p></div>
|
| 291 |
+
<div style="background-color:{bg_col}; color:white; padding:15px; margin-top:10px; border-radius:12px; text-align:center; font-weight:bold;">{icon} {status}</div>"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
else:
|
| 293 |
+
html = f"<div style='color:red'>{str(res)}</div>"
|
| 294 |
+
|
| 295 |
+
yield "Done", alloc_df, xai_plot, html
|
| 296 |
except Exception as e:
|
| 297 |
import traceback
|
| 298 |
traceback.print_exc()
|
| 299 |
+
yield f"Error: {str(e)}", None, go.Figure(), f"Error: {str(e)}"
|
| 300 |
+
|
| 301 |
+
# Dashboard Placeholders
|
| 302 |
+
def get_dash_metrics():
|
| 303 |
+
if DASHBOARD_DATA_DF is None: return "$---", "..."
|
| 304 |
+
cum_ret = (1 + DASHBOARD_DATA_DF['Daily_Ret_Eq'].fillna(0)).cumprod()
|
| 305 |
+
curr = 100000 * cum_ret.iloc[-1]
|
| 306 |
+
last = DASHBOARD_DATA_DF['Daily_Ret_Eq'].iloc[-1] * 100
|
| 307 |
+
col = "#10b981" if last >= 0 else "#ef4444"
|
| 308 |
+
return f"${curr:,.2f}", f"<span style='color:{col}'>{last:+.2f}%</span>"
|
| 309 |
+
|
| 310 |
+
def get_hist_plot():
|
| 311 |
+
if DASHBOARD_DATA_DF is None: return go.Figure()
|
| 312 |
+
dates = DASHBOARD_DATA_DF.index
|
| 313 |
+
vals = 100000 * (1 + DASHBOARD_DATA_DF['Daily_Ret_Eq'].fillna(0)).cumprod()
|
| 314 |
+
fig = go.Figure(go.Scatter(x=dates, y=vals, mode='lines', name='Portfolio', line=dict(color='#10b981', width=2)))
|
| 315 |
+
fig.update_layout(title="Simulated Net Worth", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
return fig
|
| 317 |
|
| 318 |
+
def get_alloc_plot():
|
| 319 |
+
fig = px.pie(values=[0.2]*5, names=ASSETS, title="Target Allocation", color_discrete_sequence=px.colors.qualitative.Bold)
|
| 320 |
+
fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
|
|
|
|
|
|
|
|
|
|
| 321 |
return fig
|
| 322 |
|
| 323 |
+
def get_trans():
|
| 324 |
+
return pd.DataFrame([["2025-11-24", "REBALANCE", "ALL", "N/A"]], columns=["Date", "Type", "Asset", "Value"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
+
# --- UI ---
|
| 327 |
custom_css = """
|
| 328 |
.metric-box { background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151; text-align: center; }
|
| 329 |
+
.metric-label { font-size: 1.1em; color: #9ca3af; }
|
| 330 |
.metric-value { font-size: 2.2em; font-weight: 700; color: #e5e7eb; }
|
|
|
|
| 331 |
"""
|
| 332 |
|
| 333 |
+
# REMOVED theme= argument to fix Gradio conflict
|
| 334 |
+
with gr.Blocks(css=custom_css, title="Deep RL Manager") as demo:
|
| 335 |
+
gr.HTML("""<script>function f(){document.body.classList.add('dark');} f(); setTimeout(f, 500);</script>""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
gr.Markdown("# ๐ง Deep RL & LLM Portfolio Manager")
|
| 337 |
|
| 338 |
with gr.Tabs():
|
| 339 |
+
with gr.TabItem("๐ Dashboard"):
|
| 340 |
+
nw, ch = get_dash_metrics()
|
|
|
|
| 341 |
with gr.Row():
|
| 342 |
+
gr.HTML(f"<div class='metric-box'><div class='metric-label'>Simulated Net Worth</div><div class='metric-value'>{nw}</div></div>")
|
| 343 |
+
gr.HTML(f"<div class='metric-box'><div class='metric-label'>24h Change</div><div class='metric-value' style='color:#10b981'>{ch}</div></div>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
with gr.Row():
|
| 345 |
+
with gr.Column(scale=3): gr.Plot(value=get_hist_plot())
|
| 346 |
+
with gr.Column(scale=1): gr.Plot(value=get_alloc_plot())
|
|
|
|
|
|
|
| 347 |
with gr.Row():
|
| 348 |
+
with gr.Column(): gr.Dataframe(value=get_trans(), label="Transactions")
|
| 349 |
+
|
| 350 |
+
with gr.TabItem("๐ฎ Forecast"):
|
| 351 |
+
btn = gr.Button("๐ Run Analysis", variant="primary")
|
| 352 |
+
stat = gr.Textbox(label="Status", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
with gr.Row():
|
|
|
|
| 354 |
with gr.Column(scale=2):
|
| 355 |
+
alloc = gr.Dataframe(label="Allocation")
|
| 356 |
+
xai = gr.Plot(label="XAI")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
with gr.Column(scale=3):
|
| 358 |
+
rep = gr.HTML(label="Report")
|
| 359 |
+
btn.click(predict_and_analyze, None, [stat, alloc, xai, rep])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
|
| 361 |
+
with gr.TabItem("๐
Analyst"):
|
| 362 |
with gr.Row():
|
| 363 |
with gr.Column(scale=1):
|
| 364 |
+
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]
|
| 365 |
+
sel = gr.Dropdown(choices=ticks, multiselect=True, label="Assets")
|
| 366 |
+
per = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="Period")
|
| 367 |
+
btn = gr.Button("Analyze", variant="primary")
|
|
|
|
| 368 |
with gr.Column(scale=3):
|
| 369 |
+
plot = gr.Plot()
|
| 370 |
+
out = gr.Markdown()
|
| 371 |
+
btn.click(run_hist_analysis, [sel, per], [plot, out])
|
| 372 |
|
| 373 |
+
with gr.TabItem("๐ Simulation"):
|
| 374 |
+
with gr.Row():
|
| 375 |
+
s_d = gr.Textbox(label="Start", value="2024-01-01")
|
| 376 |
+
e_d = gr.Textbox(label="End", value="2025-01-01")
|
| 377 |
+
btn = gr.Button("Run", variant="primary")
|
| 378 |
+
stat = gr.Textbox(label="Status")
|
| 379 |
+
plot = gr.Plot()
|
| 380 |
+
met = gr.Dataframe(label="Metrics")
|
| 381 |
+
btn.click(run_historical_simulation, [s_d, e_d], [plot, stat, met])
|
| 382 |
|
| 383 |
if __name__ == "__main__":
|
| 384 |
demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, share=True)
|