-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrisk_visualization.py
More file actions
434 lines (354 loc) · 15.4 KB
/
risk_visualization.py
File metadata and controls
434 lines (354 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""
Risk Visualization Components Module
Advanced visualization widgets for risk monitoring and drawdown tracking.
"""
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib.patches import Wedge, Circle
import pandas as pd
import numpy as np
from typing import Optional, List, Tuple
import customtkinter as ctk
from logger import system_logger
import config
class RiskGauge:
"""
Circular gauge widget for displaying risk metrics.
"""
def __init__(self, parent, title="Risk", max_value=100, threshold=75, width=3, height=3):
"""
Initialize risk gauge.
Args:
parent: Parent widget
title: Gauge title
max_value: Maximum value for the gauge
threshold: Warning threshold (red zone starts here)
width: Figure width in inches
height: Figure height in inches
"""
self.parent = parent
self.title = title
self.max_value = max_value
self.threshold = threshold
# Create figure
self.fig = Figure(figsize=(width, height), dpi=100)
self.fig.patch.set_facecolor('#1a1a1a')
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('#1a1a1a')
self.ax.set_aspect('equal')
self.ax.axis('off')
# Create canvas
self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
self.canvas_widget = self.canvas.get_tk_widget()
# Initial draw
self.update(0)
def update(self, value: float):
"""
Update gauge with new value.
Args:
value: Current value to display
"""
try:
self.ax.clear()
self.ax.set_aspect('equal')
self.ax.axis('off')
# Calculate angle (gauge goes from -120 to 120 degrees)
pct = min(value / self.max_value, 1.0)
angle = -120 + (240 * pct)
# Draw gauge background (gray arc)
bg_wedge = Wedge(
(0, 0), 1, -120, 120,
width=0.3, facecolor='#333', edgecolor='none'
)
self.ax.add_patch(bg_wedge)
# Determine color based on value
threshold_pct = self.threshold / self.max_value
if pct < threshold_pct * 0.5:
color = '#00ff88' # Green - safe
elif pct < threshold_pct:
color = '#ffa500' # Orange - warning
else:
color = '#ff3333' # Red - danger
# Draw value arc
if pct > 0:
value_wedge = Wedge(
(0, 0), 1, -120, angle,
width=0.3, facecolor=color, edgecolor='none'
)
self.ax.add_patch(value_wedge)
# Draw center circle
center = Circle((0, 0), 0.7, facecolor='#1a1a1a', edgecolor='none')
self.ax.add_patch(center)
# Add value text
self.ax.text(
0, 0.1, f'{value:.1f}%',
ha='center', va='center',
color='white', fontsize=20, fontweight='bold'
)
# Add title
self.ax.text(
0, -0.3, self.title,
ha='center', va='center',
color='white', fontsize=12
)
# Add min/max labels
self.ax.text(
-0.85, -0.7, '0',
ha='center', va='center',
color='gray', fontsize=9
)
self.ax.text(
0.85, -0.7, f'{self.max_value}',
ha='center', va='center',
color='gray', fontsize=9
)
# Set limits
self.ax.set_xlim(-1.2, 1.2)
self.ax.set_ylim(-1.2, 1.2)
self.fig.tight_layout()
self.canvas.draw()
except Exception as e:
system_logger.error(f"Error updating risk gauge: {str(e)}")
def pack(self, **kwargs):
"""Pack the canvas widget"""
self.canvas_widget.pack(**kwargs)
def grid(self, **kwargs):
"""Grid the canvas widget"""
self.canvas_widget.grid(**kwargs)
class DrawdownChart:
"""
Enhanced portfolio chart with drawdown visualization.
"""
def __init__(self, parent, width=8, height=5):
"""
Initialize drawdown chart.
Args:
parent: Parent widget
width: Figure width in inches
height: Figure height in inches
"""
self.parent = parent
# Create figure with two subplots
self.fig = Figure(figsize=(width, height), dpi=100)
self.fig.patch.set_facecolor('#1a1a1a')
# Main equity curve
self.ax_equity = self.fig.add_subplot(211)
self.ax_equity.set_facecolor('#2b2b2b')
# Drawdown subplot
self.ax_drawdown = self.fig.add_subplot(212, sharex=self.ax_equity)
self.ax_drawdown.set_facecolor('#2b2b2b')
# Styling
for ax in [self.ax_equity, self.ax_drawdown]:
ax.tick_params(colors='white')
ax.spines['bottom'].set_color('white')
ax.spines['left'].set_color('white')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.grid(True, alpha=0.2, color='gray')
# Create canvas
self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
self.canvas_widget = self.canvas.get_tk_widget()
# Initial empty plot
self.ax_equity.set_title('Portfolio Equity & Drawdown', color='white', fontsize=12, fontweight='bold')
self.ax_equity.set_ylabel('Equity ($)', color='white')
self.ax_drawdown.set_xlabel('Time', color='white')
self.ax_drawdown.set_ylabel('Drawdown (%)', color='white')
def update(self, timestamps: List, values: List, trades: Optional[List] = None):
"""
Update chart with equity and drawdown data.
Args:
timestamps: List of datetime objects
values: List of portfolio values
trades: Optional list of trade markers (buy/sell points)
"""
try:
self.ax_equity.clear()
self.ax_drawdown.clear()
if len(timestamps) > 0 and len(values) > 0:
values_array = np.array(values)
# Calculate running peak and drawdown
running_peak = np.maximum.accumulate(values_array)
drawdown = ((running_peak - values_array) / running_peak) * 100
# Plot equity curve
self.ax_equity.plot(timestamps, values, color='#00ff88', linewidth=2, label='Equity')
self.ax_equity.plot(timestamps, running_peak, color='cyan', linewidth=1, alpha=0.5, linestyle='--', label='Peak')
# Shade drawdown periods on equity chart
# Find drawdown periods
in_drawdown = drawdown > 0
if np.any(in_drawdown):
self.ax_equity.fill_between(
timestamps, values, running_peak,
where=in_drawdown,
alpha=0.3, color='red', label='Drawdown'
)
# Add trade markers if provided
if trades:
buy_times = [t['time'] for t in trades if t['action'] == 'BUY']
buy_prices = [t['price'] for t in trades if t['action'] == 'BUY']
sell_times = [t['time'] for t in trades if t['action'] == 'SELL']
sell_prices = [t['price'] for t in trades if t['action'] == 'SELL']
if buy_times:
self.ax_equity.scatter(buy_times, buy_prices, color='lime', marker='^', s=100, zorder=5, label='Buy')
if sell_times:
self.ax_equity.scatter(sell_times, sell_prices, color='red', marker='v', s=100, zorder=5, label='Sell')
# Plot drawdown
self.ax_drawdown.fill_between(timestamps, 0, -drawdown, color='red', alpha=0.5)
self.ax_drawdown.plot(timestamps, -drawdown, color='darkred', linewidth=1.5)
# Add circuit breaker threshold line
threshold = config.MAX_DRAWDOWN_THRESHOLD * 100
self.ax_drawdown.axhline(y=-threshold, color='yellow', linestyle='--', linewidth=2, label=f'Circuit Breaker ({threshold}%)')
# Styling
self.ax_equity.set_title('Portfolio Equity & Drawdown', color='white', fontsize=12, fontweight='bold')
self.ax_equity.set_ylabel('Equity ($)', color='white')
self.ax_equity.legend(loc='upper left', facecolor='#2b2b2b', edgecolor='white', labelcolor='white', fontsize=8)
self.ax_equity.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x:,.0f}'))
self.ax_drawdown.set_xlabel('Date', color='white')
self.ax_drawdown.set_ylabel('Drawdown (%)', color='white')
self.ax_drawdown.legend(loc='lower left', facecolor='#2b2b2b', edgecolor='white', labelcolor='white', fontsize=8)
# Rotate x-axis labels
plt.setp(self.ax_drawdown.xaxis.get_majorticklabels(), rotation=45, ha='right')
else:
self.ax_equity.text(0.5, 0.5, 'No Data Available',
ha='center', va='center', color='gray', fontsize=14,
transform=self.ax_equity.transAxes)
self.fig.tight_layout()
self.canvas.draw()
except Exception as e:
system_logger.error(f"Error updating drawdown chart: {str(e)}")
def pack(self, **kwargs):
"""Pack the canvas widget"""
self.canvas_widget.pack(**kwargs)
def grid(self, **kwargs):
"""Grid the canvas widget"""
self.canvas_widget.grid(**kwargs)
class RiskDashboard:
"""
Comprehensive risk monitoring dashboard with gauges and indicators.
"""
def __init__(self, parent):
"""
Initialize risk dashboard.
Args:
parent: Parent widget
"""
self.frame = ctk.CTkFrame(parent)
# Title
title = ctk.CTkLabel(
self.frame,
text="🛡️ Risk Monitoring Dashboard",
font=ctk.CTkFont(size=16, weight="bold")
)
title.grid(row=0, column=0, columnspan=3, pady=10, padx=10, sticky="ew")
# Create gauges
gauge_frame = ctk.CTkFrame(self.frame)
gauge_frame.grid(row=1, column=0, columnspan=3, pady=10, padx=10, sticky="ew")
# Drawdown gauge
self.drawdown_gauge = RiskGauge(
gauge_frame,
title="Current Drawdown",
max_value=config.MAX_DRAWDOWN_THRESHOLD * 100,
threshold=config.MAX_DRAWDOWN_THRESHOLD * 100 * 0.75
)
self.drawdown_gauge.grid(row=0, column=0, padx=10, pady=10)
# Daily loss gauge
self.daily_loss_gauge = RiskGauge(
gauge_frame,
title="Daily Loss",
max_value=config.MAX_DAILY_LOSS * 100,
threshold=config.MAX_DAILY_LOSS * 100 * 0.75
)
self.daily_loss_gauge.grid(row=0, column=1, padx=10, pady=10)
# Position utilization gauge
self.position_gauge = RiskGauge(
gauge_frame,
title="Position Utilization",
max_value=100,
threshold=80
)
self.position_gauge.grid(row=0, column=2, padx=10, pady=10)
# Status indicators
status_frame = ctk.CTkFrame(self.frame)
status_frame.grid(row=2, column=0, columnspan=3, pady=10, padx=10, sticky="ew")
# Circuit breaker status
ctk.CTkLabel(
status_frame,
text="Circuit Breaker:",
font=ctk.CTkFont(size=12, weight="bold")
).grid(row=0, column=0, padx=10, pady=5, sticky="e")
self.circuit_breaker_label = ctk.CTkLabel(
status_frame,
text="✅ OK",
font=ctk.CTkFont(size=12),
text_color="green"
)
self.circuit_breaker_label.grid(row=0, column=1, padx=10, pady=5, sticky="w")
# Peak equity
ctk.CTkLabel(
status_frame,
text="Peak Equity:",
font=ctk.CTkFont(size=12, weight="bold")
).grid(row=1, column=0, padx=10, pady=5, sticky="e")
self.peak_equity_label = ctk.CTkLabel(
status_frame,
text="$0.00",
font=ctk.CTkFont(size=12)
)
self.peak_equity_label.grid(row=1, column=1, padx=10, pady=5, sticky="w")
# Max drawdown
ctk.CTkLabel(
status_frame,
text="Max Drawdown:",
font=ctk.CTkFont(size=12, weight="bold")
).grid(row=2, column=0, padx=10, pady=5, sticky="e")
self.max_drawdown_label = ctk.CTkLabel(
status_frame,
text="0.0%",
font=ctk.CTkFont(size=12)
)
self.max_drawdown_label.grid(row=2, column=1, padx=10, pady=5, sticky="w")
def update(self, risk_report: dict):
"""
Update dashboard with risk report data.
Args:
risk_report: Risk report dictionary from RiskManager
"""
try:
# Update gauges
current_dd = risk_report.get('current_drawdown', 0)
self.drawdown_gauge.update(current_dd)
daily_loss = abs(risk_report.get('daily_loss_pct', 0))
self.daily_loss_gauge.update(daily_loss)
position_util = risk_report.get('position_utilization', 0)
self.position_gauge.update(position_util)
# Update status
trading_halted = risk_report.get('trading_halted', False)
if trading_halted:
self.circuit_breaker_label.configure(
text="🚨 HALTED",
text_color="red"
)
else:
self.circuit_breaker_label.configure(
text="✅ OK",
text_color="green"
)
# Update peak equity
peak = risk_report.get('peak_equity', 0)
if peak:
self.peak_equity_label.configure(text=f"${peak:,.2f}")
# Update max drawdown
max_dd = risk_report.get('max_drawdown', 0)
color = "green" if max_dd < 5 else ("orange" if max_dd < 10 else "red")
self.max_drawdown_label.configure(
text=f"{max_dd:.2f}%",
text_color=color
)
except Exception as e:
system_logger.error(f"Error updating risk dashboard: {str(e)}")
def pack(self, **kwargs):
"""Pack the frame"""
self.frame.pack(**kwargs)
def grid(self, **kwargs):
"""Grid the frame"""
self.frame.grid(**kwargs)