-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart_matplotlib_60m.py
More file actions
499 lines (439 loc) · 21.4 KB
/
chart_matplotlib_60m.py
File metadata and controls
499 lines (439 loc) · 21.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
"""
Bloomberg Terminal-Style Elliott Wave Chart — 60-Minute Intraday (Max History)
Downloads 60m data in chunks to maximize available history, then runs backtest.
"""
import sys
sys.argv = [sys.argv[0], "60m"]
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from matplotlib.gridspec import GridSpec
from matplotlib.lines import Line2D
from datetime import datetime, timedelta
sys.path.insert(0, "E:/Developer/lufftw/repo/stock")
from elliott_wave_backtest import (
find_swing_points, merge_swing_points,
detect_impulse_waves, detect_corrective_waves,
run_backtest, SYMBOL, INITIAL_CAPITAL, Trade
)
# ── Chunked download for maximum 60m history ──────────────────
def fetch_60m_max_history(symbol: str, years: int = 5) -> pd.DataFrame:
"""
Download 60m data in chunks to get maximum available history.
Yahoo Finance limits intraday data to ~730 days from today.
We try 59-day chunks going back as far as possible.
"""
end_date = datetime.now()
target_start = end_date - timedelta(days=years * 365)
chunk_days = 59 # yfinance allows ~60 days per intraday request
all_chunks = []
current_end = end_date
print(f"Attempting to download {symbol} 60m data from "
f"{target_start.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}...")
print(f"(Yahoo Finance limits intraday data to ~730 days)\n")
attempt = 0
max_attempts = (years * 365) // chunk_days + 5 # safety limit
consecutive_empty = 0
while current_end > target_start and attempt < max_attempts:
current_start = current_end - timedelta(days=chunk_days)
if current_start < target_start:
current_start = target_start
attempt += 1
try:
chunk = yf.download(
symbol,
start=current_start.strftime("%Y-%m-%d"),
end=current_end.strftime("%Y-%m-%d"),
interval="60m",
progress=False,
)
if chunk is not None and not chunk.empty:
if isinstance(chunk.columns, pd.MultiIndex):
chunk.columns = chunk.columns.get_level_values(0)
all_chunks.append(chunk)
n = len(chunk)
print(f" Chunk {attempt}: {current_start.strftime('%Y-%m-%d')} ~ "
f"{current_end.strftime('%Y-%m-%d')} => {n} bars")
consecutive_empty = 0
else:
consecutive_empty += 1
if consecutive_empty >= 3:
print(f" No more data available beyond this point.")
break
except Exception as e:
print(f" Chunk {attempt} error: {e}")
consecutive_empty += 1
if consecutive_empty >= 3:
break
current_end = current_start
if not all_chunks:
raise ValueError(f"Failed to download any 60m data for {symbol}")
# Concatenate and deduplicate
df = pd.concat(all_chunks)
df = df[~df.index.duplicated(keep="first")]
df = df.sort_index()
df = df.dropna()
print(f"\nTotal: {len(df)} bars, "
f"range {df.index[0].strftime('%Y-%m-%d')} ~ {df.index[-1].strftime('%Y-%m-%d')}")
return df
# ── Bloomberg-style Color Palette ──────────────────────────────
BG_COLOR = "#0D1117"
PANEL_BG = "#161B22"
GRID_COLOR = "#21262D"
TEXT_COLOR = "#C9D1D9"
TEXT_DIM = "#8B949E"
ACCENT_ORANGE = "#FF9800"
ACCENT_CYAN = "#00BCD4"
ACCENT_GREEN = "#00E676"
ACCENT_RED = "#FF1744"
IMPULSE_COLOR = "#00E5FF"
CORRECT_COLOR = "#FF6D00"
ZIGZAG_COLOR = "#5C6BC0"
UP_CANDLE = "#26A69A"
DOWN_CANDLE = "#EF5350"
UP_VOL = "#26A69A"
DOWN_VOL = "#EF5350"
EQUITY_COLOR = "#42A5F5"
DRAWDOWN_COLOR = "#EF5350"
LONG_MARKER = "#00E676"
SHORT_MARKER = "#E040FB"
WIN_EXIT = "#76FF03"
LOSS_EXIT = "#FF1744"
def build_equity_curve(trades, df):
equity = INITIAL_CAPITAL
dates = [df.index[0]]
values = [equity]
for t in trades:
equity *= (1 + t.pnl_pct / 100)
if t.exit_date is not None:
dates.append(t.exit_date)
values.append(equity)
if dates[-1] != df.index[-1]:
dates.append(df.index[-1])
values.append(equity)
return dates, values
def compute_drawdown(dates, values):
arr = np.array(values)
running_max = np.maximum.accumulate(arr)
drawdown_pct = (running_max - arr) / running_max * 100
return drawdown_pct
def draw_ohlc_bars(ax, df):
dates = mdates.date2num(df.index.to_pydatetime())
opens = df["Open"].values
highs = df["High"].values
lows = df["Low"].values
closes = df["Close"].values
if len(dates) > 1:
median_gap = np.median(np.diff(dates))
tick_width = median_gap * 0.3
else:
tick_width = 0.005
for i in range(len(df)):
color = UP_CANDLE if closes[i] >= opens[i] else DOWN_CANDLE
ax.plot([dates[i], dates[i]], [lows[i], highs[i]],
color=color, linewidth=0.4, solid_capstyle="round")
ax.plot([dates[i] - tick_width, dates[i]], [opens[i], opens[i]],
color=color, linewidth=0.5, solid_capstyle="butt")
ax.plot([dates[i], dates[i] + tick_width], [closes[i], closes[i]],
color=color, linewidth=0.5, solid_capstyle="butt")
def main():
# ── 1. Download max 60m Data ──────────────────────────────
df = fetch_60m_max_history(SYMBOL, years=5)
# ── 2. Run backtest & wave detection ──────────────────────
result = run_backtest(df)
trades = result["trades"]
zigzag = result["zigzag"]
impulse_waves = result["impulse_waves"]
corrective_waves = result["corrective_waves"]
print(f"\nImpulse waves detected: {len(impulse_waves)}")
print(f"Corrective waves detected: {len(corrective_waves)}")
print(f"Trades executed: {len(trades)}")
# ── Print performance report ──────────────────────────────
if trades:
total_trades = len(trades)
wins = [t for t in trades if t.pnl > 0]
losses = [t for t in trades if t.pnl <= 0]
win_rate = len(wins) / total_trades * 100
total_pnl_pct = sum(t.pnl_pct for t in trades)
avg_pnl = total_pnl_pct / total_trades
avg_win = np.mean([t.pnl_pct for t in wins]) if wins else 0
avg_loss = np.mean([t.pnl_pct for t in losses]) if losses else 0
equity = INITIAL_CAPITAL
eq_curve = [equity]
for t in trades:
equity *= (1 + t.pnl_pct / 100)
eq_curve.append(equity)
max_eq = eq_curve[0]
max_dd = 0
for e in eq_curve:
if e > max_eq:
max_eq = e
dd = (max_eq - e) / max_eq * 100
if dd > max_dd:
max_dd = dd
bh_return = (df["Close"].iloc[-1] / df["Close"].iloc[0] - 1) * 100
print(f"\n{'=' * 70}")
print(f" 波浪理論回測績效報表(60分K)")
print(f"{'=' * 70}")
print(f"\n 期間: {df.index[0].strftime('%Y-%m-%d')} ~ {df.index[-1].strftime('%Y-%m-%d')}")
print(f" K線總數: {len(df)}")
print(f" 總交易次數: {total_trades}")
print(f" 做多: {sum(1 for t in trades if t.direction == 'long')}")
print(f" 做空: {sum(1 for t in trades if t.direction == 'short')}")
print(f" 勝率: {win_rate:.1f}%")
print(f" 平均每筆報酬: {avg_pnl:.2f}%")
print(f" 平均獲利(贏): {avg_win:.2f}%")
print(f" 平均虧損(輸): {avg_loss:.2f}%")
print(f" 累計報酬: {total_pnl_pct:.2f}%")
print(f" 最大回撤: {max_dd:.2f}%")
print(f" 最終淨值: {eq_curve[-1]:,.0f}")
print(f" 買入持有報酬: {bh_return:.2f}%")
print(f"\n {'交易明細':─^64}")
print(f" {'#':>3} {'方向':>4} {'進場日期':>18} {'出場日期':>18} "
f"{'進場價':>10} {'出場價':>10} {'報酬%':>8}")
print(f" {'─' * 76}")
for i, t in enumerate(trades, 1):
d = "多" if t.direction == "long" else "空"
entry_d = t.entry_date.strftime("%Y-%m-%d %H:%M") if t.entry_date else ""
exit_d = t.exit_date.strftime("%Y-%m-%d %H:%M") if t.exit_date else ""
print(f" {i:>3} {d:>4} {entry_d:>18} {exit_d:>18} "
f"{t.entry_price:>10.1f} {t.exit_price:>10.1f} {t.pnl_pct:>+8.2f}%")
print(f"{'=' * 70}")
else:
print("\n 無交易紀錄")
# ── 3. Build equity curve ─────────────────────────────────
eq_dates, eq_values = build_equity_curve(trades, df)
drawdown = compute_drawdown(eq_dates, eq_values)
# ── 4. Create Figure ──────────────────────────────────────
plt.style.use("dark_background")
plt.rcParams.update({
"font.family": "Consolas",
"font.size": 9,
"axes.labelsize": 10,
"axes.titlesize": 12,
"xtick.labelsize": 7,
"ytick.labelsize": 8,
"legend.fontsize": 7,
"figure.facecolor": BG_COLOR,
"axes.facecolor": PANEL_BG,
"axes.edgecolor": GRID_COLOR,
"grid.color": GRID_COLOR,
"grid.alpha": 0.5,
"text.color": TEXT_COLOR,
"axes.labelcolor": TEXT_COLOR,
"xtick.color": TEXT_DIM,
"ytick.color": TEXT_DIM,
})
fig = plt.figure(figsize=(24, 14), facecolor=BG_COLOR)
gs = GridSpec(4, 1, figure=fig, height_ratios=[5, 1.2, 1.8, 1.0],
hspace=0.08, left=0.05, right=0.97, top=0.93, bottom=0.05)
ax_price = fig.add_subplot(gs[0])
ax_vol = fig.add_subplot(gs[1], sharex=ax_price)
ax_equity = fig.add_subplot(gs[2])
ax_dd = fig.add_subplot(gs[3], sharex=ax_equity)
# ═══════════════════════════════════════════════════════════
# PANEL 1: OHLC Price Chart with Elliott Wave Labels
# ═══════════════════════════════════════════════════════════
draw_ohlc_bars(ax_price, df)
if zigzag:
zz_dates = [df.index[p[0]] for p in zigzag]
zz_prices = [p[1] for p in zigzag]
ax_price.plot(zz_dates, zz_prices, color=ZIGZAG_COLOR,
linewidth=1.0, alpha=0.6, label="ZigZag", zorder=3)
price_range = df["High"].max() - df["Low"].min()
annot_offset = max(25, min(50, price_range * 0.002))
for w in impulse_waves:
pts = w.points
wave_dates = [df.index[p[0]] for p in pts]
wave_prices = [p[1] for p in pts]
ax_price.plot(wave_dates, wave_prices, color=IMPULSE_COLOR,
linewidth=1.8, alpha=0.8, zorder=4)
labels = ["0", "1", "2", "3", "4", "5"]
for j, (idx, price) in enumerate(pts):
va = "bottom" if j % 2 == 1 else "top"
offset_y = annot_offset if j % 2 == 1 else -annot_offset
ax_price.annotate(
labels[j],
xy=(df.index[idx], price),
xytext=(0, offset_y),
textcoords="offset points",
fontsize=9, fontweight="bold", color=IMPULSE_COLOR,
ha="center", va=va,
bbox=dict(boxstyle="round,pad=0.15", facecolor=BG_COLOR,
edgecolor=IMPULSE_COLOR, alpha=0.85, linewidth=0.7),
arrowprops=dict(arrowstyle="-", color=IMPULSE_COLOR,
alpha=0.3, linewidth=0.5),
zorder=6,
)
for w in corrective_waves:
pts = w.points
wave_dates = [df.index[p[0]] for p in pts]
wave_prices = [p[1] for p in pts]
ax_price.plot(wave_dates, wave_prices, color=CORRECT_COLOR,
linewidth=1.8, alpha=0.8, linestyle="--", zorder=4)
labels = ["A", "B", "C"]
display_pts = [(pts[0][0], pts[0][1]),
(pts[2][0], pts[2][1]),
(pts[3][0], pts[3][1])]
for j, (idx, price) in enumerate(display_pts):
va = "top" if j in [0] else ("bottom" if j == 1 else "top")
offset_y = -annot_offset if va == "top" else annot_offset
ax_price.annotate(
labels[j],
xy=(df.index[idx], price),
xytext=(0, offset_y),
textcoords="offset points",
fontsize=9, fontweight="bold", color=CORRECT_COLOR,
ha="center", va=va,
bbox=dict(boxstyle="round,pad=0.15", facecolor=BG_COLOR,
edgecolor=CORRECT_COLOR, alpha=0.85, linewidth=0.7),
arrowprops=dict(arrowstyle="-", color=CORRECT_COLOR,
alpha=0.3, linewidth=0.5),
zorder=6,
)
for t in trades:
if t.direction == "long":
ax_price.scatter(t.entry_date, t.entry_price, marker="^",
color=LONG_MARKER, s=100, zorder=7,
edgecolors="white", linewidths=0.5)
else:
ax_price.scatter(t.entry_date, t.entry_price, marker="v",
color=SHORT_MARKER, s=100, zorder=7,
edgecolors="white", linewidths=0.5)
if t.exit_date is not None:
exit_color = WIN_EXIT if t.pnl > 0 else LOSS_EXIT
ax_price.scatter(t.exit_date, t.exit_price, marker="X",
color=exit_color, s=80, zorder=7,
edgecolors="white", linewidths=0.4)
ax_price.set_ylabel("Price (TWD)", fontweight="bold")
ax_price.yaxis.set_major_formatter(mticker.FuncFormatter(
lambda x, _: f"{x:,.0f}"))
ax_price.grid(True, alpha=0.3, linewidth=0.5)
ax_price.tick_params(axis="x", labelbottom=False)
legend_elements = [
Line2D([0], [0], color=UP_CANDLE, linewidth=2, label="Up Bar"),
Line2D([0], [0], color=DOWN_CANDLE, linewidth=2, label="Down Bar"),
Line2D([0], [0], color=ZIGZAG_COLOR, linewidth=1.2, label="ZigZag"),
Line2D([0], [0], color=IMPULSE_COLOR, linewidth=2, label="Impulse (1-5)"),
Line2D([0], [0], color=CORRECT_COLOR, linewidth=2, linestyle="--",
label="Corrective (ABC)"),
Line2D([0], [0], marker="^", color=LONG_MARKER, linestyle="None",
markersize=8, label="Long Entry"),
Line2D([0], [0], marker="v", color=SHORT_MARKER, linestyle="None",
markersize=8, label="Short Entry"),
Line2D([0], [0], marker="X", color=WIN_EXIT, linestyle="None",
markersize=8, label="Win Exit"),
Line2D([0], [0], marker="X", color=LOSS_EXIT, linestyle="None",
markersize=8, label="Loss Exit"),
]
ax_price.legend(handles=legend_elements, loc="upper left",
framealpha=0.85, facecolor=PANEL_BG, edgecolor=GRID_COLOR,
ncol=3, columnspacing=1.0)
# ═══════════════════════════════════════════════════════════
# PANEL 2: Volume Bars
# ═══════════════════════════════════════════════════════════
closes = df["Close"].values
opens = df["Open"].values
volumes = df["Volume"].values
colors_vol = [UP_VOL if closes[i] >= opens[i] else DOWN_VOL
for i in range(len(df))]
dates_num = mdates.date2num(df.index.to_pydatetime())
if len(dates_num) > 1:
vol_bar_width = np.median(np.diff(dates_num)) * 0.7
else:
vol_bar_width = 0.01
max_vol = max(volumes) if max(volumes) > 0 else 1
ax_vol.bar(dates_num, volumes, width=vol_bar_width, color=colors_vol,
alpha=0.7, edgecolor="none")
ax_vol.set_ylabel("Volume", fontweight="bold")
ax_vol.yaxis.set_major_formatter(mticker.FuncFormatter(
lambda x, _: f"{x/1e9:.1f}B" if x >= 1e9 else (
f"{x/1e6:.0f}M" if x >= 1e6 else f"{x:,.0f}")))
ax_vol.grid(True, alpha=0.3, linewidth=0.5)
ax_vol.tick_params(axis="x", labelbottom=False)
ax_vol.set_ylim(0, max_vol * 1.3)
ax_vol.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax_vol.xaxis.set_major_locator(mdates.MonthLocator())
# ═══════════════════════════════════════════════════════════
# PANEL 3: Equity Curve
# ═══════════════════════════════════════════════════════════
if len(eq_dates) > 1:
ax_equity.plot(eq_dates, eq_values, color=EQUITY_COLOR,
linewidth=1.8, zorder=3, label="Portfolio Equity")
ax_equity.fill_between(eq_dates, INITIAL_CAPITAL, eq_values,
where=[v >= INITIAL_CAPITAL for v in eq_values],
color=ACCENT_GREEN, alpha=0.08, interpolate=True)
ax_equity.fill_between(eq_dates, INITIAL_CAPITAL, eq_values,
where=[v < INITIAL_CAPITAL for v in eq_values],
color=ACCENT_RED, alpha=0.08, interpolate=True)
ax_equity.axhline(INITIAL_CAPITAL, color=TEXT_DIM, linestyle="--",
linewidth=0.6, alpha=0.6)
final_eq = eq_values[-1]
total_return = (final_eq / INITIAL_CAPITAL - 1) * 100
ax_equity.annotate(
f" {final_eq:,.0f} ({total_return:+.1f}%)",
xy=(eq_dates[-1], final_eq),
fontsize=9, fontweight="bold",
color=ACCENT_GREEN if total_return >= 0 else ACCENT_RED,
va="center",
)
ax_equity.set_ylabel("Equity (TWD)", fontweight="bold")
ax_equity.yaxis.set_major_formatter(mticker.FuncFormatter(
lambda x, _: f"{x/1e6:.2f}M" if x >= 1e6 else f"{x:,.0f}"))
ax_equity.grid(True, alpha=0.3, linewidth=0.5)
ax_equity.tick_params(axis="x", labelbottom=False)
ax_equity.legend(loc="upper left", framealpha=0.85, facecolor=PANEL_BG,
edgecolor=GRID_COLOR)
# ═══════════════════════════════════════════════════════════
# PANEL 4: Drawdown
# ═══════════════════════════════════════════════════════════
if len(eq_dates) > 1:
ax_dd.fill_between(eq_dates, 0, -drawdown, color=DRAWDOWN_COLOR,
alpha=0.4, step="post")
ax_dd.plot(eq_dates, -drawdown, color=DRAWDOWN_COLOR,
linewidth=0.8, alpha=0.8)
max_dd = max(drawdown)
ax_dd.axhline(0, color=TEXT_DIM, linewidth=0.5, alpha=0.4)
if max_dd > 0:
ax_dd.annotate(
f" Max DD: {max_dd:.1f}%",
xy=(eq_dates[np.argmax(drawdown)], -max_dd),
fontsize=8, fontweight="bold", color=DRAWDOWN_COLOR,
va="top",
)
ax_dd.set_ylabel("Drawdown %", fontweight="bold")
ax_dd.set_xlabel("Date", fontweight="bold")
ax_dd.grid(True, alpha=0.3, linewidth=0.5)
ax_dd.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax_dd.xaxis.set_major_locator(mdates.MonthLocator())
plt.setp(ax_dd.xaxis.get_majorticklabels(), rotation=0, ha="center")
# ── Title Bar ─────────────────────────────────────────────
win_count = sum(1 for t in trades if t.pnl > 0)
total_count = len(trades)
win_rate = (win_count / total_count * 100) if total_count > 0 else 0
total_pnl = sum(t.pnl_pct for t in trades)
title_text = (
f"ELLIOTT WAVE BACKTEST | {SYMBOL} | 60m | "
f"{df.index[0].strftime('%Y-%m-%d')} to {df.index[-1].strftime('%Y-%m-%d')} | "
f"Bars: {len(df)} | Trades: {total_count} | Win Rate: {win_rate:.0f}% | "
f"Return: {total_pnl:+.1f}%"
)
fig.suptitle(title_text, fontsize=12, fontweight="bold",
color=ACCENT_ORANGE, y=0.97,
fontfamily="Consolas")
fig.text(0.5, 0.945,
"Taiwan Weighted Index | 60-Min | Impulse (1-5) & Corrective (A-B-C) Wave Detection",
ha="center", fontsize=9, color=TEXT_DIM, fontfamily="Consolas")
# ── Save ──────────────────────────────────────────────────
output_path = "E:/Developer/lufftw/repo/stock/chart_matplotlib_60m.png"
fig.savefig(output_path, dpi=200, facecolor=BG_COLOR,
edgecolor="none", bbox_inches="tight")
plt.close(fig)
print(f"\nChart saved to: {output_path}")
if __name__ == "__main__":
main()