-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart_components.py
More file actions
303 lines (238 loc) · 10.4 KB
/
chart_components.py
File metadata and controls
303 lines (238 loc) · 10.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
"""
Chart Components Module
Professional charting widgets for the trading platform.
"""
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import mplfinance as mpf
import pandas as pd
from typing import Optional
import customtkinter as ctk
from logger import system_logger
class PortfolioChart:
"""
Portfolio equity curve chart component.
"""
def __init__(self, parent, width=6, height=4):
"""
Initialize portfolio chart.
Args:
parent: Parent widget
width: Figure width in inches
height: Figure height in inches
"""
self.parent = parent
# 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('#2b2b2b')
self.ax.tick_params(colors='white')
self.ax.spines['bottom'].set_color('white')
self.ax.spines['left'].set_color('white')
self.ax.spines['top'].set_visible(False)
self.ax.spines['right'].set_visible(False)
# Create canvas
self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
self.canvas_widget = self.canvas.get_tk_widget()
# Initial empty plot
self.ax.set_title('Portfolio Value', color='white', fontsize=12, fontweight='bold')
self.ax.set_xlabel('Time', color='white')
self.ax.set_ylabel('Value ($)', color='white')
self.ax.grid(True, alpha=0.2, color='gray')
def update(self, timestamps, values):
"""
Update chart with new data.
Args:
timestamps: List of datetime objects
values: List of portfolio values
"""
try:
self.ax.clear()
if len(timestamps) > 0 and len(values) > 0:
# Plot line
self.ax.plot(timestamps, values, color='#00ff88', linewidth=2)
# Fill area under curve
self.ax.fill_between(timestamps, values, alpha=0.3, color='#00ff88')
# Styling
self.ax.set_title('Portfolio Value', color='white', fontsize=12, fontweight='bold')
self.ax.set_xlabel('Time', color='white')
self.ax.set_ylabel('Value ($)', color='white')
self.ax.grid(True, alpha=0.2, color='gray')
self.ax.tick_params(colors='white')
# Format y-axis as currency
self.ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x:,.0f}'))
# Rotate x-axis labels
plt.setp(self.ax.xaxis.get_majorticklabels(), rotation=45, ha='right')
else:
self.ax.text(0.5, 0.5, 'No Data Available',
ha='center', va='center', color='gray', fontsize=14,
transform=self.ax.transAxes)
self.fig.tight_layout()
self.canvas.draw()
except Exception as e:
system_logger.error(f"Error updating portfolio 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 PriceChart:
"""
Price chart with technical indicators.
"""
def __init__(self, parent, width=8, height=5):
"""
Initialize price chart.
Args:
parent: Parent widget
width: Figure width in inches
height: Figure height in inches
"""
self.parent = parent
# Create figure with subplots
self.fig = Figure(figsize=(width, height), dpi=100)
self.fig.patch.set_facecolor('#1a1a1a')
# Price subplot
self.ax_price = self.fig.add_subplot(211)
self.ax_price.set_facecolor('#2b2b2b')
# Volume subplot
self.ax_volume = self.fig.add_subplot(212, sharex=self.ax_price)
self.ax_volume.set_facecolor('#2b2b2b')
# Styling
for ax in [self.ax_price, self.ax_volume]:
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()
def update(self, df: pd.DataFrame, symbol: str):
"""
Update chart with price data.
Args:
df: DataFrame with OHLCV data
symbol: Stock symbol
"""
try:
self.ax_price.clear()
self.ax_volume.clear()
if df is not None and len(df) > 0:
# Ensure index is datetime
if not isinstance(df.index, pd.DatetimeIndex):
df.index = pd.to_datetime(df.index)
# Plot price line
self.ax_price.plot(df.index, df['Close'], color='#00ff88', linewidth=2, label='Close')
# Plot moving averages if available
if 'SMA_20' in df.columns:
self.ax_price.plot(df.index, df['SMA_20'], color='orange', linewidth=1, alpha=0.7, label='SMA 20')
if 'SMA_50' in df.columns:
self.ax_price.plot(df.index, df['SMA_50'], color='blue', linewidth=1, alpha=0.7, label='SMA 50')
# Plot volume bars
colors = ['green' if close >= open_ else 'red'
for close, open_ in zip(df['Close'], df['Open'])]
self.ax_volume.bar(df.index, df['Volume'], color=colors, alpha=0.5, width=0.8)
# Titles and labels
self.ax_price.set_title(f'{symbol} Price Chart', color='white', fontsize=12, fontweight='bold')
self.ax_price.set_ylabel('Price ($)', color='white')
self.ax_price.legend(loc='upper left', facecolor='#2b2b2b', edgecolor='white', labelcolor='white')
self.ax_volume.set_xlabel('Date', color='white')
self.ax_volume.set_ylabel('Volume', color='white')
# Format y-axis
self.ax_price.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x:.2f}'))
self.ax_volume.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'{x/1e6:.1f}M' if x >= 1e6 else f'{x/1e3:.0f}K'))
# Rotate x-axis labels
plt.setp(self.ax_volume.xaxis.get_majorticklabels(), rotation=45, ha='right')
else:
self.ax_price.text(0.5, 0.5, 'No Data Available',
ha='center', va='center', color='gray', fontsize=14,
transform=self.ax_price.transAxes)
self.fig.tight_layout()
self.canvas.draw()
except Exception as e:
system_logger.error(f"Error updating price 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 PerformanceMetrics:
"""
Performance metrics display component.
"""
def __init__(self, parent):
"""
Initialize metrics display.
Args:
parent: Parent widget
"""
self.frame = ctk.CTkFrame(parent)
# Create metric labels
self.metrics = {}
metrics_config = [
("Total Trades", "total_trades"),
("Win Rate", "win_rate"),
("Avg Win", "avg_win"),
("Avg Loss", "avg_loss"),
("Total P&L", "total_pnl"),
("Best Trade", "best_trade"),
]
row = 0
col = 0
for label, key in metrics_config:
# Label
ctk.CTkLabel(
self.frame,
text=label + ":",
font=ctk.CTkFont(size=11, weight="bold")
).grid(row=row, column=col, padx=10, pady=5, sticky="e")
# Value
value_label = ctk.CTkLabel(
self.frame,
text="0",
font=ctk.CTkFont(size=11)
)
value_label.grid(row=row, column=col+1, padx=10, pady=5, sticky="w")
self.metrics[key] = value_label
row += 1
if row >= 3:
row = 0
col += 2
def update(self, stats: dict):
"""
Update metrics display.
Args:
stats: Dictionary of statistics
"""
try:
self.metrics['total_trades'].configure(text=str(stats.get('total_trades', 0)))
win_rate = stats.get('win_rate', 0)
self.metrics['win_rate'].configure(
text=f"{win_rate:.1f}%",
text_color="green" if win_rate >= 50 else "red"
)
avg_win = stats.get('avg_win', 0)
self.metrics['avg_win'].configure(text=f"${avg_win:.2f}")
avg_loss = stats.get('avg_loss', 0)
self.metrics['avg_loss'].configure(text=f"${avg_loss:.2f}")
total_pnl = stats.get('total_pnl', 0)
self.metrics['total_pnl'].configure(
text=f"${total_pnl:,.2f}",
text_color="green" if total_pnl >= 0 else "red"
)
best_trade = stats.get('best_trade', 0)
self.metrics['best_trade'].configure(text=f"${best_trade:.2f}")
except Exception as e:
system_logger.error(f"Error updating metrics: {str(e)}")
def pack(self, **kwargs):
"""Pack the frame"""
self.frame.pack(**kwargs)
def grid(self, **kwargs):
"""Grid the frame"""
self.frame.grid(**kwargs)