通达信预警回测

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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
export default {
async fetch(request) {
const url = new URL(request.url);

// ==========================================
// 代理路由:保持 3 级容错分发不变
// ==========================================
if (url.pathname === "/api/kline") {
const code = url.searchParams.get("code");
const prefix = url.searchParams.get("prefix");
const provider = url.searchParams.get("provider");

let targetUrl = "";

if (provider === "em") {
const secid = (prefix === "sh" ? "1." : "0.") + code;
targetUrl = `https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${secid}&klt=101&fqt=1&end=20500000&lmt=320&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61`;
} else if (provider === "sina") {
targetUrl = `https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketData.getKLineData?symbol=${prefix}${code}&scale=240&ma=no&datalen=320`;
} else {
targetUrl = `https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=${prefix}${code},day,,,320,qfq`;
}

try {
const fetchRes = await fetch(targetUrl, {
headers: { "User-Agent": "Mozilla/5.0" }
});
const data = await fetchRes.arrayBuffer();

return new Response(data, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
},
});
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: { "Access-Control-Allow-Origin": "*" } });
}
}

// ==========================================
// 前端 HTML 界面
// ==========================================
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>量化策略回测终端</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
:root { --up: #ef4444; --down: #22c55e; --bg-main: #0f172a; --bg-card: #1e293b; }
body { background-color: var(--bg-main); color: #f1f5f9; font-family: 'Inter', system-ui, sans-serif; }
.card { background: var(--bg-card); border: 1px solid #334155; border-radius: 1rem; }
.input-dark { background: #0f172a; border: 1px solid #475569; color: #38bdf8; font-weight: 700; padding: 0.5rem; border-radius: 0.5rem; color-scheme: dark; transition: all 0.2s ease;}
.input-dark:focus { border-color: #3b82f6; outline: none; box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3); }
.btn-primary { background: #2563eb; transition: all 0.2s; }
.btn-primary:hover { background: #3b82f6; transform: translateY(-1px); }
.btn-primary:disabled { background: #64748b; cursor: not-allowed; }
.btn-warning { background: #ea580c; transition: all 0.2s; }
.btn-warning:hover { background: #f97316; transform: translateY(-1px); }
.radio-custom:checked + div { border-color: #3b82f6; background: rgba(59, 130, 246, 0.1); }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.animate-row { animation: fadeIn 0.3s ease-out forwards; }
.group-header { cursor: pointer; user-select: none; transition: background-color 0.2s; }
.group-header:hover { background-color: #334155; }
.chevron-icon { transition: transform 0.3s ease; }
.group-open .chevron-icon { transform: rotate(180deg); }
</style>
</head>
<body class="min-h-screen p-4 md:p-8">
<div class="max-w-[1400px] mx-auto space-y-6">

<div class="card p-6 shadow-2xl w-full">
<div class="flex flex-wrap items-center justify-between gap-4 border-b border-slate-700 pb-4">
<div class="flex items-center gap-4">
<div class="bg-blue-600 p-4 rounded-xl shadow-[0_0_15px_rgba(37,99,235,0.6)]"><i class="fa-solid fa-chart-line text-2xl text-white"></i></div>
<div class="flex flex-col gap-2">
<h1 class="text-2xl font-bold tracking-tight text-white flex items-center gap-3 flex-wrap">
策略预警回测终端
<span class="bg-blue-600/90 hover:bg-blue-500 transition-colors text-white text-sm px-3 py-1 rounded-md shadow-[0_0_12px_rgba(37,99,235,0.8)] font-bold tracking-widest flex items-center gap-1.5 border border-blue-400 cursor-default">
<i class="fa-brands fa-qq text-lg"></i> 股票QQ交流群: 643618300
</span>
</h1>
</div>
</div>
<div class="flex gap-3">
<input type="file" id="fileInput" class="hidden" accept=".txt">
<button id="importBtn" onclick="document.getElementById('fileInput').click()" class="bg-slate-700 hover:bg-slate-600 px-5 py-2.5 rounded-lg border border-slate-500 transition-colors font-medium shadow-md">
<i class="fa-solid fa-file-import mr-2"></i>上传数据 (TXT)
</button>
<button id="runBtn" disabled class="btn-primary px-6 py-2.5 rounded-lg font-bold shadow-lg shadow-blue-900/50">
<i class="fa-solid fa-play mr-2"></i>开始回测
</button>
</div>
</div>

<div class="grid grid-cols-1 md:grid-cols-4 gap-6 pt-6">
<div class="space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-blue-500 pl-2">查询与筛选</h3>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">数量 (空/0查全部):</label>
<input type="number" id="limitCount" placeholder="全部" min="0" class="input-dark w-24 text-center text-sm shadow-inner">
</div>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">预警时段 (过滤):</label>
<div class="flex items-center gap-1">
<input type="time" id="startTime" class="input-dark text-xs p-1 shadow-inner">
<span class="text-slate-500 font-bold">-</span>
<input type="time" id="endTime" class="input-dark text-xs p-1 shadow-inner">
</div>
</div>
</div>

<div class="md:col-span-3 space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-purple-500 pl-2">结算价提取基准</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode1" checked class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">① 预警当日</div>
<div class="text-[10px] text-slate-400 leading-tight">提取预警当天的收盘价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode2" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">② 最新实时</div>
<div class="text-[10px] text-slate-400 leading-tight">提取股票当下的最新价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode3" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">③ 单日偏移</div>
<div id="customDaysUi" class="flex gap-2 opacity-30 pointer-events-none transition-opacity">
<div class="flex items-center gap-1">
<span class="text-[10px]">向后偏移</span>
<input type="number" id="nextDays" value="1" min="1" max="20" class="input-dark w-12 p-1 text-center text-xs">
<span class="text-[10px]">个交易日</span>
</div>
</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode4" class="peer hidden radio-custom">
<div class="border border-purple-600 rounded-lg p-3 hover:border-purple-400 transition-colors h-full flex flex-col justify-center bg-purple-900/20 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-purple-300 mb-1">④ 连续三日追踪</div>
<div class="text-[10px] text-slate-400 leading-tight">T+0至T+2每日独立涨跌</div>
</div>
</label>
</div>
</div>
</div>
</div>

<div id="progressBox" class="hidden card p-6 border border-blue-900 shadow-[0_0_15px_rgba(59,130,246,0.1)] w-full">
<div class="flex justify-between items-center text-xs mb-2 text-blue-300">
<div class="flex items-center gap-2">
<span id="progressText" class="font-medium">初始化引擎中...</span>
<span id="sourceBadge" class="hidden px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-all duration-200"></span>
</div>
<span id="progressPercent" class="font-mono font-bold">0%</span>
</div>
<div class="w-full bg-slate-800 rounded-full h-2">
<div id="progressBar" class="bg-gradient-to-r from-blue-600 to-blue-400 h-2 rounded-full transition-all duration-300 shadow-[0_0_10px_rgba(59,130,246,0.8)]" style="width: 0%"></div>
</div>
</div>

<div id="results" class="space-y-6 pb-10 w-full">
<div class="text-center py-20 text-slate-600 border-2 border-dashed border-slate-700 rounded-2xl bg-slate-800/50">
<i class="fa-solid fa-inbox text-5xl mb-4 opacity-50"></i>
<p class="text-sm">尚未导入数据。请上传包含预警信息的 TXT 文件。</p>
</div>
</div>
</div>

<div id="actionButtons" class="hidden fixed bottom-8 right-8 z-50 flex flex-col gap-3">
<button id="screenshotBtn" class="bg-indigo-600 hover:bg-indigo-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(79,70,229,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-camera"></i> 保存长图
</button>
<button id="exportBtn" class="bg-emerald-600 hover:bg-emerald-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(16,185,129,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-file-excel"></i> 导出 CSV
</button>
</div>

<script>
const API_URL = "/api/kline";

let rawContent = "";
let finalData = [];
let globalRunId = 0;
let currentRunMode = "";

function getDynamicFileName(extension) {
const limit = document.getElementById('limitCount').value;
const limitStr = (!limit || parseInt(limit) === 0) ? "全部" : limit + "只";
const st = document.getElementById('startTime').value || "09:30";
const et = document.getElementById('endTime').value || "15:00";
const timeStr = st.replace(':', '') + "-" + et.replace(':', '');
let modeStr = "";
if (currentRunMode === 'mode1') modeStr = "当日";
else if (currentRunMode === 'mode2') modeStr = "实时";
else if (currentRunMode === 'mode3') modeStr = "偏移";
else if (currentRunMode === 'mode4') modeStr = "连续追踪";

const dateStr = new Date().toLocaleDateString().replace(/\\//g, '');
return \`量化复盘_[\${limitStr}]_[\${timeStr}]_[\${modeStr}]_\${dateStr}.\${extension}\`;
}

document.querySelectorAll('input[name="timeMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const customUi = document.getElementById('customDaysUi');
if (e.target.value === 'mode3') customUi.classList.remove('opacity-30', 'pointer-events-none');
else customUi.classList.add('opacity-30', 'pointer-events-none');
});
});

document.getElementById('fileInput').addEventListener('change', function(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
const uint8 = new Uint8Array(event.target.result);
rawContent = new TextDecoder('gb18030').decode(uint8);
document.getElementById('runBtn').disabled = false;
document.getElementById('importBtn').innerHTML = '<i class="fa-solid fa-check mr-2 text-emerald-400"></i>文件已就绪 (' + file.name + ')';
};
reader.readAsArrayBuffer(file);
});

const delay = ms => new Promise(res => setTimeout(res, ms));

document.getElementById('runBtn').addEventListener('click', async function() {
globalRunId++;
const currentRunId = globalRunId;

const resultsDiv = document.getElementById('results');
const progressBox = document.getElementById('progressBox');
const runBtn = this;

resultsDiv.innerHTML = "";
finalData = [];
progressBox.classList.remove('hidden');
document.getElementById('actionButtons').classList.add('hidden');

runBtn.innerHTML = '<i class="fa-solid fa-rotate-right fa-spin mr-2"></i>中断重试';
runBtn.classList.remove('btn-primary');
runBtn.classList.add('btn-warning');

const limit = parseInt(document.getElementById('limitCount').value) || 999999;
const startTime = document.getElementById('startTime').value;
const endTime = document.getElementById('endTime').value;
const timeMode = document.querySelector('input[name="timeMode"]:checked').value;
currentRunMode = timeMode;
const nextDays = parseInt(document.getElementById('nextDays').value) || 0;

const lines = rawContent.split(/\\r?\\n/);
let strategyMap = new Map();

lines.forEach(line => {
const rawParts = line.trim().split(/\\t|\\s{2,}/);
const parts = rawParts.filter(p => p.trim() !== '');

if (parts.length < 5) return;

const code = parts[0].trim();
const name = parts[1].trim();

let dateIdx = -1;
for(let j = 2; j < parts.length; j++) {
if(parts[j].match(/^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}/)) {
dateIdx = j;
break;
}
}
if (dateIdx === -1) return;

let dateTimeStr = parts[dateIdx].trim();
let date, time, priceIdx;

if (dateTimeStr.includes(' ')) {
let dtParts = dateTimeStr.split(/\\s+/);
date = dtParts[0];
time = dtParts[1] || "15:00";
priceIdx = dateIdx + 1;
} else {
date = parts[dateIdx].trim();
time = parts[dateIdx+1].trim();
priceIdx = dateIdx + 2;
}

const price = parseFloat(parts[priceIdx]);
if(isNaN(price)) return;

const strategy = parts[parts.length - 1].trim();

if (startTime && time < startTime) return;
if (endTime && time > endTime) return;

if (!strategyMap.has(strategy)) strategyMap.set(strategy, []);
strategyMap.get(strategy).push({ code, name, date, time, price, strategy });
});

const strategies = Array.from(strategyMap.keys());
if(strategies.length === 0) {
alert("未解析到符合条件的数据,请检查格式或时间过滤段!");
resetButton(runBtn);
progressBox.classList.add('hidden');
return;
}

let processedCount = 0;
const totalToProcess = Array.from(strategyMap.values()).reduce((sum, arr) => sum + Math.min(arr.length, limit), 0);
let groupIndex = 0;

for (const sName of strategies) {
if (currentRunId !== globalRunId) return;

let group = strategyMap.get(sName);
group.sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time));
group = group.slice(0, limit);
const processedGroup = [];

for (let i = 0; i < group.length; i += 5) {
if (currentRunId !== globalRunId) return;

const chunk = group.slice(i, i + 5);
const chunkRes = await Promise.all(chunk.map(async item => {
const result = await fetchAndCalculate(item, timeMode, nextDays);
processedCount++;
if (currentRunId === globalRunId) {
updateProgress(processedCount, totalToProcess, \`查询分析中 [\${sName}]: \${item.name}\`, result.provider);
}
return result;
}));

if (currentRunId !== globalRunId) return;
processedGroup.push(...chunkRes);
await delay(50);
}

if (currentRunId !== globalRunId) return;
renderStrategyGroup(sName, processedGroup, groupIndex++, timeMode);
finalData.push({ strategy: sName, items: processedGroup, timeMode });
}

if (currentRunId === globalRunId) {
resetButton(runBtn);
updateProgress(100, 100, "分析计算完成!");
document.getElementById('actionButtons').classList.remove('hidden');
}
});

function resetButton(btn) {
btn.innerHTML = '<i class="fa-solid fa-play mr-2"></i>开始回测';
btn.classList.remove('btn-warning');
btn.classList.add('btn-primary');
}

function updateProgress(cur, total, text, provider) {
const p = total === 0 ? 100 : Math.floor((cur / total) * 100);
document.getElementById('progressBar').style.width = p + "%";
document.getElementById('progressPercent').innerText = p + "%";
document.getElementById('progressText').innerText = text;

const badge = document.getElementById('sourceBadge');
if (p >= 100) {
badge.classList.add('hidden');
} else if (provider && provider !== '无') {
badge.classList.remove('hidden');
badge.innerText = provider;
badge.className = "px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-colors ";
if (provider === '东') badge.className += "bg-red-500/80";
else if (provider === '腾') badge.className += "bg-blue-500/80";
else if (provider === '新') badge.className += "bg-yellow-600/80";
}
}

const toYYYYMMDD = (dStr) => {
const matches = String(dStr).match(/(\\d{4})[-/]?(\\d{1,2})[-/]?(\\d{1,2})/);
if (matches) {
return matches[1] + matches[2].padStart(2, '0') + matches[3].padStart(2, '0');
}
return String(dStr).replace(/\\D/g, '');
};

async function fetchAndCalculate(stock, mode, next) {
const getPrefix = (c) => {
if (c.startsWith('60') || c.startsWith('68')) return 'sh';
if (c.startsWith('00') || c.startsWith('30')) return 'sz';
if (c.startsWith('8') || c.startsWith('43') || c.startsWith('92') || c.startsWith('87')) return 'bj';
return 'sz';
};
const prefix = getPrefix(stock.code);
const fullCode = prefix + stock.code;

const fetchEM = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=em&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.data && json.data.klines && json.data.klines.length > 0) {
const kData = json.data.klines.map(line => {
const parts = line.split(',');
return [parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]];
});
return { kData, provider: '东' };
}
throw new Error("EM None");
};

const fetchTX = async () => {
if (prefix === 'bj') throw new Error("TX skip BJ");
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=tx&_=\${Date.now()}\`);
const json = await res.json();
let kData = json.data[fullCode]?.qfqday || json.data[fullCode]?.day;
if (kData && kData.length > 0) {
const qtData = json.data[fullCode].qt?.[fullCode];
if (qtData) {
const qtDateStr = qtData[30].substring(0, 8);
const formattedQtDate = qtDateStr.substring(0,4) + "-" + qtDateStr.substring(4,6) + "-" + qtDateStr.substring(6,8);
const currentPrice = parseFloat(qtData[3]);
if (kData[kData.length - 1][0] !== formattedQtDate && currentPrice > 0) {
kData.push([formattedQtDate, qtData[5], qtData[3], qtData[33], qtData[34], qtData[36]]);
}
}
return { kData, provider: '腾' };
}
throw new Error("TX None");
};

const fetchSina = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=sina&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.length > 0) {
const kData = json.map(item => [item.day.split(' ')[0], item.open, item.close, item.high, item.low, item.volume]);
return { kData, provider: '新' };
}
throw new Error("Sina None");
};

const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const bjTime = new Date(utc + (3600000 * 8));
const h = bjTime.getHours();
const m = bjTime.getMinutes();
const timeVal = h * 100 + m;

const isTradingTime = timeVal >= 915 && timeVal < 1500;

let fetchResult = null;

try {
if (isTradingTime) {
try { fetchResult = await fetchEM(); }
catch (e1) {
try { fetchResult = await fetchTX(); }
catch (e2) { fetchResult = await fetchSina(); }
}
} else {
fetchResult = await new Promise((resolve, reject) => {
let errCount = 0;
const checkReject = () => { errCount++; if (errCount === 3) reject(new Error("All APIs failed")); };
fetchEM().then(resolve).catch(checkReject);
fetchTX().then(resolve).catch(checkReject);
fetchSina().then(resolve).catch(checkReject);
});
}

const { kData, provider } = fetchResult;
const normBaseDate = toYYYYMMDD(stock.date);

let baseIdx = -1;
if (mode !== 'mode2') {
for (let i = 0; i < kData.length; i++) {
if (toYYYYMMDD(kData[i][0]) === normBaseDate) {
baseIdx = i; break;
}
}
if (baseIdx === -1) {
for (let i = kData.length - 1; i >= 0; i--) {
if (toYYYYMMDD(kData[i][0]) < normBaseDate) {
baseIdx = i; break;
}
}
}
if (baseIdx === -1) throw new Error("Date Out of Range");
}

const alertPrice = stock.price;

if (mode === 'mode4') {
const day1 = kData[baseIdx];
const day2 = baseIdx + 1 < kData.length ? kData[baseIdx + 1] : null;
const day3 = baseIdx + 2 < kData.length ? kData[baseIdx + 2] : null;

const d1Close = parseFloat(day1[2]);
const d1Profit = ((d1Close - alertPrice) / alertPrice) * 100;

let d2Close = null, d2Profit = null;
if (day2) {
d2Close = parseFloat(day2[2]);
d2Profit = ((d2Close - d1Close) / d1Close) * 100;
}

let d3Close = null, d3Profit = null;
if (day3) {
d3Close = parseFloat(day3[2]);
d3Profit = ((d3Close - d2Close) / d2Close) * 100;
}

const finalClose = d3Close || d2Close || d1Close;
const totalProfit = ((finalClose - alertPrice) / alertPrice) * 100;
const daysAvailable = 1 + (day2 ? 1 : 0) + (day3 ? 1 : 0);

return {
...stock,
d1Close, d1Profit, d1Date: day1[0].substring(5),
d2Close, d2Profit, d2Date: day2 ? day2[0].substring(5) : null,
d3Close, d3Profit, d3Date: day3 ? day3[0].substring(5) : null,
closePrice: finalClose,
profitRatio: totalProfit,
isWin: totalProfit > 0,
isTie: totalProfit === 0,
matchedDate: (day3 || day2 || day1)[0].substring(5),
daysAvailable: daysAvailable,
error: false,
provider: provider
};
}

let targetIdx = -1;
if (mode === 'mode2') targetIdx = kData.length - 1;
else if (mode === 'mode1') targetIdx = baseIdx;
else if (mode === 'mode3') {
targetIdx = baseIdx + next;
if (targetIdx >= kData.length) throw new Error("Target Future Date Not Exists");
}

if (targetIdx < 0) targetIdx = 0;
const closePrice = parseFloat(kData[targetIdx][2]);
const matchedDateStr = kData[targetIdx][0].substring(5);

const profitDiff = closePrice - alertPrice;
const profitRatio = (profitDiff / alertPrice) * 100;

return {
...stock,
closePrice: closePrice,
profitRatio: profitRatio,
isWin: profitDiff > 0,
isTie: profitDiff === 0,
matchedDate: matchedDateStr,
error: false,
provider: provider
};
} catch (e) {
return { ...stock, closePrice: stock.price, profitRatio: 0, isWin: false, isTie: false, error: true, daysAvailable: 0, provider: '无' };
}
}

window.toggleAccordion = function(id) {
const allBodies = document.querySelectorAll('.strategy-body');
allBodies.forEach(body => {
if (body.id === id) {
body.classList.toggle('hidden');
body.previousElementSibling.classList.toggle('group-open');
} else {
body.classList.add('hidden');
body.previousElementSibling.classList.remove('group-open');
}
});
};

function renderStrategyGroup(strategyName, list, groupId, timeMode) {
const container = document.getElementById('results');
const validStocks = list.filter(i => !i.error);
const totalValidCount = validStocks.length;

let totalProfitRatioSum = 0;
let winCount = 0;

let sumD1 = 0, countD1 = 0;
let sumD2 = 0, countD2 = 0;
let sumD3 = 0, countD3 = 0;

validStocks.forEach(i => {
totalProfitRatioSum += i.profitRatio;
if(i.isWin) winCount++;

if (timeMode === 'mode4') {
if (i.d1Profit !== null && i.d1Profit !== undefined) { sumD1 += i.d1Profit; countD1++; }
if (i.d2Profit !== null && i.d2Profit !== undefined) { sumD2 += i.d2Profit; countD2++; }
if (i.d3Profit !== null && i.d3Profit !== undefined) { sumD3 += i.d3Profit; countD3++; }
}
});

const strategyTotalProfitRatio = totalValidCount > 0 ? (totalProfitRatioSum / totalValidCount).toFixed(2) : "0.00";
const winRate = totalValidCount > 0 ? ((winCount / totalValidCount) * 100).toFixed(1) : "0.0";

const profitColorClass = strategyTotalProfitRatio > 0 ? 'text-red-500' : strategyTotalProfitRatio < 0 ? 'text-green-500' : 'text-slate-300';
const profitSign = strategyTotalProfitRatio > 0 ? '+' : '';

const maxDays = totalValidCount > 0 ? Math.max(1, ...validStocks.map(s => s.daysAvailable || 1)) : 1;
const refStock = validStocks[0] || {};
const refD1 = refStock.d1Date || '--';
const refD2 = refStock.d2Date || '--';
const refD3 = refStock.d3Date || '--';

let mode4HeaderHtml = '';
let theadHtml = '';

if (timeMode === 'mode4') {
const avgD1 = countD1 > 0 ? (sumD1 / countD1).toFixed(2) : "0.00";
const avgD2 = countD2 > 0 ? (sumD2 / countD2).toFixed(2) : "0.00";
const avgD3 = countD3 > 0 ? (sumD3 / countD3).toFixed(2) : "0.00";

mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-6 text-sm items-center flex-wrap justify-end w-full lg:w-auto mt-2 lg:mt-0">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center"><span class="text-slate-400 text-xs uppercase mb-1">有效股票</span><span class="text-white font-mono text-base font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+0</span><span class="font-mono text-sm font-bold my-0.5 \${avgD1 > 0 ? 'text-red-500' : avgD1 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD1 > 0 ? '+' : ''}\${avgD1}%</span><span class="text-blue-300 text-xs">(\${refD1})</span></div>\`;
if (maxDays >= 2) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+1</span><span class="font-mono text-sm font-bold my-0.5 \${avgD2 > 0 ? 'text-red-500' : avgD2 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD2 > 0 ? '+' : ''}\${avgD2}%</span><span class="text-blue-300 text-xs">(\${refD2})</span></div>\`;
if (maxDays >= 3) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+2</span><span class="font-mono text-sm font-bold my-0.5 \${avgD3 > 0 ? 'text-red-500' : avgD3 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD3 > 0 ? '+' : ''}\${avgD3}%</span><span class="text-blue-300 text-xs">(\${refD3})</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4"><span class="text-purple-400 text-xs uppercase font-bold mb-1">累计总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-lg">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">预警价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+0 (当日)</th>\`;
if (maxDays >= 2) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+1 (次日)</th>\`;
if (maxDays >= 3) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+2 (三日)</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right text-purple-300 whitespace-nowrap">累计盈亏</th>\`;
} else {
mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-8 text-sm items-center">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">有效股票数</span><span class="text-white font-mono font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">胜率</span><span class="text-white font-mono font-bold">\${winRate}%</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">策略总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-base">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">文档买入价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">结算收盘价 <span class="text-[9px] text-slate-500 normal-case tracking-normal">(取值日期)</span></th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">单只盈亏比</th>\`;
}

let tbodyHtml = '';
list.forEach(i => {
const pColor = i.profitRatio > 0 ? 'text-red-500' : i.profitRatio < 0 ? 'text-green-500' : 'text-slate-400';
const statusTag = i.error ? '<span class="px-2 py-1 rounded bg-slate-500/30 text-slate-400 border border-slate-500/50 whitespace-nowrap">未收录</span>' :
i.isWin ? '<span class="px-2 py-1 rounded bg-red-500/10 text-red-500 border border-red-500/20 whitespace-nowrap">盈利</span>' :
i.isTie ? '<span class="px-2 py-1 rounded bg-slate-500/10 text-slate-400 border border-slate-500/20 whitespace-nowrap">平盘</span>' :
'<span class="px-2 py-1 rounded bg-green-500/10 text-green-500 border border-green-500/20 whitespace-nowrap">亏损</span>';

let rowInnerHtml = '';
if (timeMode === 'mode4') {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap align-middle">\${i.price.toFixed(2)}</td>\`;

if (i.error) {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 2) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 3) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
} else {
const c1 = i.d1Profit > 0 ? 'text-red-500' : i.d1Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d1Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c1} py-0.5">\${(i.d1Profit>0?'+':'')}\${i.d1Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d1Date})</div>
</td>\`;

if (maxDays >= 2) {
if (i.d2Close) {
const c2 = i.d2Profit > 0 ? 'text-red-500' : i.d2Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d2Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c2} py-0.5">\${(i.d2Profit>0?'+':'')}\${i.d2Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d2Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 3) {
if (i.d3Close) {
const c3 = i.d3Profit > 0 ? 'text-red-500' : i.d3Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d3Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c3} py-0.5">\${(i.d3Profit>0?'+':'')}\${i.d3Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d3Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
}
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} text-sm whitespace-nowrap align-middle">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap">\${i.price.toFixed(2)}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono text-slate-300 whitespace-nowrap">\${i.error ? '--' : \`\${i.closePrice.toFixed(2)} <br><span class="text-[10px] text-slate-500 font-bold">(\${i.matchedDate})</span>\`}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} whitespace-nowrap">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
}

tbodyHtml += \`
<tr class="hover:bg-slate-800/60 transition-colors \${i.error ? 'opacity-40' : ''}">
<td class="p-4 align-middle">
<div class="text-blue-400 font-bold whitespace-nowrap">\${i.code}</div>
<div class="text-slate-300 whitespace-nowrap flex items-center gap-1">
\${i.name}
<span class="text-[10px] text-slate-600 opacity-50 font-normal cursor-default select-none">\${i.provider || ''}</span>
</div>
</td>
<td class="p-4 text-slate-400 font-mono whitespace-nowrap align-middle">\${i.date} \${i.time}</td>
\${rowInnerHtml}
<td class="p-4 text-center text-[10px] font-bold align-middle">\${statusTag}</td>
</tr>
\`;
});

const groupHtml = \`
<div class="card overflow-hidden shadow-xl animate-row border border-slate-700 w-full">
<div class="group-header bg-slate-800 p-4 border-b border-slate-700 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4" onclick="toggleAccordion('body-\${groupId}')">
<div class="flex items-center gap-3">
<i class="fa-solid fa-chevron-down chevron-icon text-slate-400"></i>
<span class="bg-indigo-600/30 text-indigo-300 text-xs px-2 py-1 rounded border border-indigo-500/30 font-bold truncate max-w-[200px]" title="\${strategyName}">
\${strategyName}
</span>
\${totalValidCount < list.length ? \`<span class="text-[10px] bg-red-900/40 text-red-400 px-2 py-0.5 rounded border border-red-800/50">屏蔽 \${list.length - totalValidCount} 支无数据</span>\` : ''}
</div>
\${mode4HeaderHtml}
</div>

<div id="body-\${groupId}" class="strategy-body hidden overflow-x-auto bg-[#172033]">
<table class="w-full text-xs text-left">
<thead class="text-slate-400 bg-slate-900/50 uppercase">
<tr>
<th class="p-4 font-medium whitespace-nowrap">股票信息</th>
<th class="p-4 font-medium whitespace-nowrap">预警时间</th>
\${theadHtml}
<th class="p-4 font-medium text-center whitespace-nowrap">状态</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-800/50">
\${tbodyHtml}
</tbody>
</table>
</div>
</div>
\`;
container.insertAdjacentHTML('beforeend', groupHtml);

list.strategyTotalProfitRatio = strategyTotalProfitRatio;
list.validCount = totalValidCount;
}

document.getElementById('screenshotBtn').addEventListener('click', async function() {
const btn = this;
const originalHTML = btn.innerHTML;
const resultsDiv = document.getElementById('results');

btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> 生成图中...';
btn.disabled = true;

try {
const canvas = await html2canvas(resultsDiv, {
backgroundColor: '#0f172a',
scale: 3,
useCORS: true,
logging: false,
allowTaint: true
});

const imgData = canvas.toDataURL('image/png', 1.0);
const link = document.createElement('a');
link.href = imgData;
link.download = getDynamicFileName('png');
link.click();
} catch (err) {
alert("生成图片失败: " + err.message);
} finally {
btn.innerHTML = originalHTML;
btn.disabled = false;
}
});

document.getElementById('exportBtn').onclick = () => {
let csv = "";

finalData.forEach(group => {
const timeMode = group.timeMode;
const maxD = timeMode === 'mode4' ? Math.max(1, ...group.items.filter(i=>!i.error).map(s=>s.daysAvailable||1)) : 1;

if (timeMode === 'mode4') {
csv += "\\ufeff预警时间,股票代码,股票名称,文档预警价,T+0取值日期,T+0收盘价,T+0单日盈亏";
if (maxD >= 2) csv += ",T+1取值日期,T+1收盘价,T+1单日盈亏";
if (maxD >= 3) csv += ",T+2取值日期,T+2收盘价,T+2单日盈亏";
csv += ",累计总盈亏,状态,策略名称\\n";
} else {
csv += "\\ufeff预警时间,股票代码,股票名称,文档买入基准,结算收盘价,取价日期,单只盈亏比,状态,策略名称\\n";
}

group.items.forEach(s => {
const status = s.error ? "未收录" : (s.isWin ? "盈利" : s.isTie ? "平盘" : "亏损");

if (timeMode === 'mode4') {
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\`;
csv += \`"\${s.error ? '--' : s.d1Date}",\${s.error ? 0 : s.d1Close.toFixed(2)},\${s.error ? 0 : s.d1Profit.toFixed(2)}%,\`;
if (maxD >= 2) csv += \`"\${s.d2Date||'--'}",\${s.d2Close ? s.d2Close.toFixed(2) : '--'},\${s.d2Profit ? s.d2Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 3) csv += \`"\${s.d3Date||'--'}",\${s.d3Close ? s.d3Close.toFixed(2) : '--'},\${s.d3Profit ? s.d3Profit.toFixed(2) + '%' : '--'},\`;
csv += \`\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
} else {
const mDate = s.error ? "--" : s.matchedDate;
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\${s.error ? 0 : s.closePrice.toFixed(2)},"\${mDate}",\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
}
});

csv += \`"统计信息","有效股票数量:\${group.items.validCount}",,,,,"策略总盈亏:",\${group.items.strategyTotalProfitRatio}%,,"\${group.strategy} 汇总"\\n\\n\`;
});

const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = getDynamicFileName('csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
</script>
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html;charset=UTF-8" } });
}
};

连续追踪从 3 日改成 7 日。

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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
export default {
async fetch(request) {
const url = new URL(request.url);

// ==========================================
// 代理路由:保持 3 级容错分发不变
// ==========================================
if (url.pathname === "/api/kline") {
const code = url.searchParams.get("code");
const prefix = url.searchParams.get("prefix");
const provider = url.searchParams.get("provider");

let targetUrl = "";

if (provider === "em") {
const secid = (prefix === "sh" ? "1." : "0.") + code;
targetUrl = `https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${secid}&klt=101&fqt=1&end=20500000&lmt=320&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61`;
} else if (provider === "sina") {
targetUrl = `https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketData.getKLineData?symbol=${prefix}${code}&scale=240&ma=no&datalen=320`;
} else {
targetUrl = `https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=${prefix}${code},day,,,320,qfq`;
}

try {
const fetchRes = await fetch(targetUrl, {
headers: { "User-Agent": "Mozilla/5.0" }
});
const data = await fetchRes.arrayBuffer();

return new Response(data, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
},
});
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: { "Access-Control-Allow-Origin": "*" } });
}
}

// ==========================================
// 前端 HTML 界面
// ==========================================
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>量化策略回测终端</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
:root { --up: #ef4444; --down: #22c55e; --bg-main: #0f172a; --bg-card: #1e293b; }
body { background-color: var(--bg-main); color: #f1f5f9; font-family: 'Inter', system-ui, sans-serif; }
.card { background: var(--bg-card); border: 1px solid #334155; border-radius: 1rem; }
.input-dark { background: #0f172a; border: 1px solid #475569; color: #38bdf8; font-weight: 700; padding: 0.5rem; border-radius: 0.5rem; color-scheme: dark; transition: all 0.2s ease;}
.input-dark:focus { border-color: #3b82f6; outline: none; box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3); }
.btn-primary { background: #2563eb; transition: all 0.2s; }
.btn-primary:hover { background: #3b82f6; transform: translateY(-1px); }
.btn-primary:disabled { background: #64748b; cursor: not-allowed; }
.btn-warning { background: #ea580c; transition: all 0.2s; }
.btn-warning:hover { background: #f97316; transform: translateY(-1px); }
.radio-custom:checked + div { border-color: #3b82f6; background: rgba(59, 130, 246, 0.1); }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.animate-row { animation: fadeIn 0.3s ease-out forwards; }
.group-header { cursor: pointer; user-select: none; transition: background-color 0.2s; }
.group-header:hover { background-color: #334155; }
.chevron-icon { transition: transform 0.3s ease; }
.group-open .chevron-icon { transform: rotate(180deg); }
</style>
</head>
<body class="min-h-screen p-4 md:p-8">
<div class="max-w-[1400px] mx-auto space-y-6">

<div class="card p-6 shadow-2xl w-full">
<div class="flex flex-wrap items-center justify-between gap-4 border-b border-slate-700 pb-4">
<div class="flex items-center gap-4">
<div class="bg-blue-600 p-4 rounded-xl shadow-[0_0_15px_rgba(37,99,235,0.6)]"><i class="fa-solid fa-chart-line text-2xl text-white"></i></div>
<div class="flex flex-col gap-2">
<h1 class="text-2xl font-bold tracking-tight text-white flex items-center gap-3 flex-wrap">
策略预警回测终端
<span class="bg-blue-600/90 hover:bg-blue-500 transition-colors text-white text-sm px-3 py-1 rounded-md shadow-[0_0_12px_rgba(37,99,235,0.8)] font-bold tracking-widest flex items-center gap-1.5 border border-blue-400 cursor-default">
<i class="fa-brands fa-qq text-lg"></i> 股票QQ交流群: 643618300
</span>
</h1>
</div>
</div>
<div class="flex gap-3">
<input type="file" id="fileInput" class="hidden" accept=".txt">
<button id="importBtn" onclick="document.getElementById('fileInput').click()" class="bg-slate-700 hover:bg-slate-600 px-5 py-2.5 rounded-lg border border-slate-500 transition-colors font-medium shadow-md">
<i class="fa-solid fa-file-import mr-2"></i>上传数据 (TXT)
</button>
<button id="runBtn" disabled class="btn-primary px-6 py-2.5 rounded-lg font-bold shadow-lg shadow-blue-900/50">
<i class="fa-solid fa-play mr-2"></i>开始回测
</button>
</div>
</div>

<div class="grid grid-cols-1 md:grid-cols-4 gap-6 pt-6">
<div class="space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-blue-500 pl-2">查询与筛选</h3>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">数量 (空/0查全部):</label>
<input type="number" id="limitCount" placeholder="全部" min="0" class="input-dark w-24 text-center text-sm shadow-inner">
</div>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">预警时段 (过滤):</label>
<div class="flex items-center gap-1">
<input type="time" id="startTime" class="input-dark text-xs p-1 shadow-inner">
<span class="text-slate-500 font-bold">-</span>
<input type="time" id="endTime" class="input-dark text-xs p-1 shadow-inner">
</div>
</div>
</div>

<div class="md:col-span-3 space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-purple-500 pl-2">结算价提取基准</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode1" checked class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">① 预警当日</div>
<div class="text-[10px] text-slate-400 leading-tight">提取预警当天的收盘价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode2" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">② 最新实时</div>
<div class="text-[10px] text-slate-400 leading-tight">提取股票当下的最新价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode3" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">③ 单日偏移</div>
<div id="customDaysUi" class="flex gap-2 opacity-30 pointer-events-none transition-opacity">
<div class="flex items-center gap-1">
<span class="text-[10px]">向后偏移</span>
<input type="number" id="nextDays" value="1" min="1" max="20" class="input-dark w-12 p-1 text-center text-xs">
<span class="text-[10px]">个交易日</span>
</div>
</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode4" class="peer hidden radio-custom">
<div class="border border-purple-600 rounded-lg p-3 hover:border-purple-400 transition-colors h-full flex flex-col justify-center bg-purple-900/20 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-purple-300 mb-1">④ 连续七日追踪</div>
<div class="text-[10px] text-slate-400 leading-tight">T+0至T+6每日独立涨跌</div>
</div>
</label>
</div>
</div>
</div>
</div>

<div id="progressBox" class="hidden card p-6 border border-blue-900 shadow-[0_0_15px_rgba(59,130,246,0.1)] w-full">
<div class="flex justify-between items-center text-xs mb-2 text-blue-300">
<div class="flex items-center gap-2">
<span id="progressText" class="font-medium">初始化引擎中...</span>
<span id="sourceBadge" class="hidden px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-all duration-200"></span>
</div>
<span id="progressPercent" class="font-mono font-bold">0%</span>
</div>
<div class="w-full bg-slate-800 rounded-full h-2">
<div id="progressBar" class="bg-gradient-to-r from-blue-600 to-blue-400 h-2 rounded-full transition-all duration-300 shadow-[0_0_10px_rgba(59,130,246,0.8)]" style="width: 0%"></div>
</div>
</div>

<div id="results" class="space-y-6 pb-10 w-full">
<div class="text-center py-20 text-slate-600 border-2 border-dashed border-slate-700 rounded-2xl bg-slate-800/50">
<i class="fa-solid fa-inbox text-5xl mb-4 opacity-50"></i>
<p class="text-sm">尚未导入数据。请上传包含预警信息的 TXT 文件。</p>
</div>
</div>
</div>

<div id="actionButtons" class="hidden fixed bottom-8 right-8 z-50 flex flex-col gap-3">
<button id="screenshotBtn" class="bg-indigo-600 hover:bg-indigo-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(79,70,229,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-camera"></i> 保存长图
</button>
<button id="exportBtn" class="bg-emerald-600 hover:bg-emerald-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(16,185,129,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-file-excel"></i> 导出 CSV
</button>
</div>

<script>
const API_URL = "/api/kline";

let rawContent = "";
let finalData = [];
let globalRunId = 0;
let currentRunMode = "";

function getDynamicFileName(extension) {
const limit = document.getElementById('limitCount').value;
const limitStr = (!limit || parseInt(limit) === 0) ? "全部" : limit + "只";
const st = document.getElementById('startTime').value || "09:30";
const et = document.getElementById('endTime').value || "15:00";
const timeStr = st.replace(':', '') + "-" + et.replace(':', '');
let modeStr = "";
if (currentRunMode === 'mode1') modeStr = "当日";
else if (currentRunMode === 'mode2') modeStr = "实时";
else if (currentRunMode === 'mode3') modeStr = "偏移";
else if (currentRunMode === 'mode4') modeStr = "连续追踪";

const dateStr = new Date().toLocaleDateString().replace(/\\//g, '');
return \`量化复盘_[\${limitStr}]_[\${timeStr}]_[\${modeStr}]_\${dateStr}.\${extension}\`;
}

document.querySelectorAll('input[name="timeMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const customUi = document.getElementById('customDaysUi');
if (e.target.value === 'mode3') customUi.classList.remove('opacity-30', 'pointer-events-none');
else customUi.classList.add('opacity-30', 'pointer-events-none');
});
});

document.getElementById('fileInput').addEventListener('change', function(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
const uint8 = new Uint8Array(event.target.result);
rawContent = new TextDecoder('gb18030').decode(uint8);
document.getElementById('runBtn').disabled = false;
document.getElementById('importBtn').innerHTML = '<i class="fa-solid fa-check mr-2 text-emerald-400"></i>文件已就绪 (' + file.name + ')';
};
reader.readAsArrayBuffer(file);
});

const delay = ms => new Promise(res => setTimeout(res, ms));

document.getElementById('runBtn').addEventListener('click', async function() {
globalRunId++;
const currentRunId = globalRunId;

const resultsDiv = document.getElementById('results');
const progressBox = document.getElementById('progressBox');
const runBtn = this;

resultsDiv.innerHTML = "";
finalData = [];
progressBox.classList.remove('hidden');
document.getElementById('actionButtons').classList.add('hidden');

runBtn.innerHTML = '<i class="fa-solid fa-rotate-right fa-spin mr-2"></i>中断重试';
runBtn.classList.remove('btn-primary');
runBtn.classList.add('btn-warning');

const limit = parseInt(document.getElementById('limitCount').value) || 999999;
const startTime = document.getElementById('startTime').value;
const endTime = document.getElementById('endTime').value;
const timeMode = document.querySelector('input[name="timeMode"]:checked').value;
currentRunMode = timeMode;
const nextDays = parseInt(document.getElementById('nextDays').value) || 0;

const lines = rawContent.split(/\\r?\\n/);
let strategyMap = new Map();

lines.forEach(line => {
const rawParts = line.trim().split(/\\t|\\s{2,}/);
const parts = rawParts.filter(p => p.trim() !== '');

if (parts.length < 5) return;

const code = parts[0].trim();
const name = parts[1].trim();

let dateIdx = -1;
for(let j = 2; j < parts.length; j++) {
if(parts[j].match(/^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}/)) {
dateIdx = j;
break;
}
}
if (dateIdx === -1) return;

let dateTimeStr = parts[dateIdx].trim();
let date, time, priceIdx;

if (dateTimeStr.includes(' ')) {
let dtParts = dateTimeStr.split(/\\s+/);
date = dtParts[0];
time = dtParts[1] || "15:00";
priceIdx = dateIdx + 1;
} else {
date = parts[dateIdx].trim();
time = parts[dateIdx+1].trim();
priceIdx = dateIdx + 2;
}

const price = parseFloat(parts[priceIdx]);
if(isNaN(price)) return;

const strategy = parts[parts.length - 1].trim();

if (startTime && time < startTime) return;
if (endTime && time > endTime) return;

if (!strategyMap.has(strategy)) strategyMap.set(strategy, []);
strategyMap.get(strategy).push({ code, name, date, time, price, strategy });
});

const strategies = Array.from(strategyMap.keys());
if(strategies.length === 0) {
alert("未解析到符合条件的数据,请检查格式或时间过滤段!");
resetButton(runBtn);
progressBox.classList.add('hidden');
return;
}

let processedCount = 0;
const totalToProcess = Array.from(strategyMap.values()).reduce((sum, arr) => sum + Math.min(arr.length, limit), 0);
let groupIndex = 0;

for (const sName of strategies) {
if (currentRunId !== globalRunId) return;

let group = strategyMap.get(sName);
group.sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time));
group = group.slice(0, limit);
const processedGroup = [];

for (let i = 0; i < group.length; i += 5) {
if (currentRunId !== globalRunId) return;

const chunk = group.slice(i, i + 5);
const chunkRes = await Promise.all(chunk.map(async item => {
const result = await fetchAndCalculate(item, timeMode, nextDays);
processedCount++;
if (currentRunId === globalRunId) {
updateProgress(processedCount, totalToProcess, \`查询分析中 [\${sName}]: \${item.name}\`, result.provider);
}
return result;
}));

if (currentRunId !== globalRunId) return;
processedGroup.push(...chunkRes);
await delay(50);
}

if (currentRunId !== globalRunId) return;
renderStrategyGroup(sName, processedGroup, groupIndex++, timeMode);
finalData.push({ strategy: sName, items: processedGroup, timeMode });
}

if (currentRunId === globalRunId) {
resetButton(runBtn);
updateProgress(100, 100, "分析计算完成!");
document.getElementById('actionButtons').classList.remove('hidden');
}
});

function resetButton(btn) {
btn.innerHTML = '<i class="fa-solid fa-play mr-2"></i>开始回测';
btn.classList.remove('btn-warning');
btn.classList.add('btn-primary');
}

function updateProgress(cur, total, text, provider) {
const p = total === 0 ? 100 : Math.floor((cur / total) * 100);
document.getElementById('progressBar').style.width = p + "%";
document.getElementById('progressPercent').innerText = p + "%";
document.getElementById('progressText').innerText = text;

const badge = document.getElementById('sourceBadge');
if (p >= 100) {
badge.classList.add('hidden');
} else if (provider && provider !== '无') {
badge.classList.remove('hidden');
badge.innerText = provider;
badge.className = "px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-colors ";
if (provider === '东') badge.className += "bg-red-500/80";
else if (provider === '腾') badge.className += "bg-blue-500/80";
else if (provider === '新') badge.className += "bg-yellow-600/80";
}
}

const toYYYYMMDD = (dStr) => {
const matches = String(dStr).match(/(\\d{4})[-/]?(\\d{1,2})[-/]?(\\d{1,2})/);
if (matches) {
return matches[1] + matches[2].padStart(2, '0') + matches[3].padStart(2, '0');
}
return String(dStr).replace(/\\D/g, '');
};

async function fetchAndCalculate(stock, mode, next) {
const getPrefix = (c) => {
if (c.startsWith('60') || c.startsWith('68')) return 'sh';
if (c.startsWith('00') || c.startsWith('30')) return 'sz';
if (c.startsWith('8') || c.startsWith('43') || c.startsWith('92') || c.startsWith('87')) return 'bj';
return 'sz';
};
const prefix = getPrefix(stock.code);
const fullCode = prefix + stock.code;

const fetchEM = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=em&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.data && json.data.klines && json.data.klines.length > 0) {
const kData = json.data.klines.map(line => {
const parts = line.split(',');
return [parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]];
});
return { kData, provider: '东' };
}
throw new Error("EM None");
};

const fetchTX = async () => {
if (prefix === 'bj') throw new Error("TX skip BJ");
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=tx&_=\${Date.now()}\`);
const json = await res.json();
let kData = json.data[fullCode]?.qfqday || json.data[fullCode]?.day;
if (kData && kData.length > 0) {
const qtData = json.data[fullCode].qt?.[fullCode];
if (qtData) {
const qtDateStr = qtData[30].substring(0, 8);
const formattedQtDate = qtDateStr.substring(0,4) + "-" + qtDateStr.substring(4,6) + "-" + qtDateStr.substring(6,8);
const currentPrice = parseFloat(qtData[3]);
if (kData[kData.length - 1][0] !== formattedQtDate && currentPrice > 0) {
kData.push([formattedQtDate, qtData[5], qtData[3], qtData[33], qtData[34], qtData[36]]);
}
}
return { kData, provider: '腾' };
}
throw new Error("TX None");
};

const fetchSina = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=sina&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.length > 0) {
const kData = json.map(item => [item.day.split(' ')[0], item.open, item.close, item.high, item.low, item.volume]);
return { kData, provider: '新' };
}
throw new Error("Sina None");
};

const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const bjTime = new Date(utc + (3600000 * 8));
const h = bjTime.getHours();
const m = bjTime.getMinutes();
const timeVal = h * 100 + m;

const isTradingTime = timeVal >= 915 && timeVal < 1500;

let fetchResult = null;

try {
if (isTradingTime) {
try { fetchResult = await fetchEM(); }
catch (e1) {
try { fetchResult = await fetchTX(); }
catch (e2) { fetchResult = await fetchSina(); }
}
} else {
fetchResult = await new Promise((resolve, reject) => {
let errCount = 0;
const checkReject = () => { errCount++; if (errCount === 3) reject(new Error("All APIs failed")); };
fetchEM().then(resolve).catch(checkReject);
fetchTX().then(resolve).catch(checkReject);
fetchSina().then(resolve).catch(checkReject);
});
}

const { kData, provider } = fetchResult;
const normBaseDate = toYYYYMMDD(stock.date);

let baseIdx = -1;
if (mode !== 'mode2') {
for (let i = 0; i < kData.length; i++) {
if (toYYYYMMDD(kData[i][0]) === normBaseDate) {
baseIdx = i; break;
}
}
if (baseIdx === -1) {
for (let i = kData.length - 1; i >= 0; i--) {
if (toYYYYMMDD(kData[i][0]) < normBaseDate) {
baseIdx = i; break;
}
}
}
if (baseIdx === -1) throw new Error("Date Out of Range");
}

const alertPrice = stock.price;

if (mode === 'mode4') {
const day1 = kData[baseIdx];
const day2 = baseIdx + 1 < kData.length ? kData[baseIdx + 1] : null;
const day3 = baseIdx + 2 < kData.length ? kData[baseIdx + 2] : null;
const day4 = baseIdx + 3 < kData.length ? kData[baseIdx + 3] : null;
const day5 = baseIdx + 4 < kData.length ? kData[baseIdx + 4] : null;
const day6 = baseIdx + 5 < kData.length ? kData[baseIdx + 5] : null;
const day7 = baseIdx + 6 < kData.length ? kData[baseIdx + 6] : null;

const d1Close = parseFloat(day1[2]);
const d1Profit = ((d1Close - alertPrice) / alertPrice) * 100;

let d2Close = null, d2Profit = null;
if (day2) { d2Close = parseFloat(day2[2]); d2Profit = ((d2Close - d1Close) / d1Close) * 100; }

let d3Close = null, d3Profit = null;
if (day3) { d3Close = parseFloat(day3[2]); d3Profit = ((d3Close - d2Close) / d2Close) * 100; }

let d4Close = null, d4Profit = null;
if (day4) { d4Close = parseFloat(day4[2]); d4Profit = ((d4Close - d3Close) / d3Close) * 100; }

let d5Close = null, d5Profit = null;
if (day5) { d5Close = parseFloat(day5[2]); d5Profit = ((d5Close - d4Close) / d4Close) * 100; }

let d6Close = null, d6Profit = null;
if (day6) { d6Close = parseFloat(day6[2]); d6Profit = ((d6Close - d5Close) / d5Close) * 100; }

let d7Close = null, d7Profit = null;
if (day7) { d7Close = parseFloat(day7[2]); d7Profit = ((d7Close - d6Close) / d6Close) * 100; }

const finalClose = d7Close || d6Close || d5Close || d4Close || d3Close || d2Close || d1Close;
const totalProfit = ((finalClose - alertPrice) / alertPrice) * 100;
const daysAvailable = 1 + (day2 ? 1 : 0) + (day3 ? 1 : 0) + (day4 ? 1 : 0) + (day5 ? 1 : 0) + (day6 ? 1 : 0) + (day7 ? 1 : 0);

return {
...stock,
d1Close, d1Profit, d1Date: day1[0].substring(5),
d2Close, d2Profit, d2Date: day2 ? day2[0].substring(5) : null,
d3Close, d3Profit, d3Date: day3 ? day3[0].substring(5) : null,
d4Close, d4Profit, d4Date: day4 ? day4[0].substring(5) : null,
d5Close, d5Profit, d5Date: day5 ? day5[0].substring(5) : null,
d6Close, d6Profit, d6Date: day6 ? day6[0].substring(5) : null,
d7Close, d7Profit, d7Date: day7 ? day7[0].substring(5) : null,
closePrice: finalClose,
profitRatio: totalProfit,
isWin: totalProfit > 0,
isTie: totalProfit === 0,
matchedDate: (day7 || day6 || day5 || day4 || day3 || day2 || day1)[0].substring(5),
daysAvailable: daysAvailable,
error: false,
provider: provider
};
}

let targetIdx = -1;
if (mode === 'mode2') targetIdx = kData.length - 1;
else if (mode === 'mode1') targetIdx = baseIdx;
else if (mode === 'mode3') {
targetIdx = baseIdx + next;
if (targetIdx >= kData.length) throw new Error("Target Future Date Not Exists");
}

if (targetIdx < 0) targetIdx = 0;
const closePrice = parseFloat(kData[targetIdx][2]);
const matchedDateStr = kData[targetIdx][0].substring(5);

const profitDiff = closePrice - alertPrice;
const profitRatio = (profitDiff / alertPrice) * 100;

return {
...stock,
closePrice: closePrice,
profitRatio: profitRatio,
isWin: profitDiff > 0,
isTie: profitDiff === 0,
matchedDate: matchedDateStr,
error: false,
provider: provider
};
} catch (e) {
return { ...stock, closePrice: stock.price, profitRatio: 0, isWin: false, isTie: false, error: true, daysAvailable: 0, provider: '无' };
}
}

window.toggleAccordion = function(id) {
const allBodies = document.querySelectorAll('.strategy-body');
allBodies.forEach(body => {
if (body.id === id) {
body.classList.toggle('hidden');
body.previousElementSibling.classList.toggle('group-open');
} else {
body.classList.add('hidden');
body.previousElementSibling.classList.remove('group-open');
}
});
};

function renderStrategyGroup(strategyName, list, groupId, timeMode) {
const container = document.getElementById('results');
const validStocks = list.filter(i => !i.error);
const totalValidCount = validStocks.length;

let totalProfitRatioSum = 0;
let winCount = 0;

let sumD1 = 0, countD1 = 0;
let sumD2 = 0, countD2 = 0;
let sumD3 = 0, countD3 = 0;
let sumD4 = 0, countD4 = 0;
let sumD5 = 0, countD5 = 0;
let sumD6 = 0, countD6 = 0;
let sumD7 = 0, countD7 = 0;

validStocks.forEach(i => {
totalProfitRatioSum += i.profitRatio;
if(i.isWin) winCount++;

if (timeMode === 'mode4') {
if (i.d1Profit !== null && i.d1Profit !== undefined) { sumD1 += i.d1Profit; countD1++; }
if (i.d2Profit !== null && i.d2Profit !== undefined) { sumD2 += i.d2Profit; countD2++; }
if (i.d3Profit !== null && i.d3Profit !== undefined) { sumD3 += i.d3Profit; countD3++; }
if (i.d4Profit !== null && i.d4Profit !== undefined) { sumD4 += i.d4Profit; countD4++; }
if (i.d5Profit !== null && i.d5Profit !== undefined) { sumD5 += i.d5Profit; countD5++; }
if (i.d6Profit !== null && i.d6Profit !== undefined) { sumD6 += i.d6Profit; countD6++; }
if (i.d7Profit !== null && i.d7Profit !== undefined) { sumD7 += i.d7Profit; countD7++; }
}
});

const strategyTotalProfitRatio = totalValidCount > 0 ? (totalProfitRatioSum / totalValidCount).toFixed(2) : "0.00";
const winRate = totalValidCount > 0 ? ((winCount / totalValidCount) * 100).toFixed(1) : "0.0";

const profitColorClass = strategyTotalProfitRatio > 0 ? 'text-red-500' : strategyTotalProfitRatio < 0 ? 'text-green-500' : 'text-slate-300';
const profitSign = strategyTotalProfitRatio > 0 ? '+' : '';

const maxDays = totalValidCount > 0 ? Math.max(1, ...validStocks.map(s => s.daysAvailable || 1)) : 1;
const refStock = validStocks[0] || {};
const refD1 = refStock.d1Date || '--';
const refD2 = refStock.d2Date || '--';
const refD3 = refStock.d3Date || '--';
const refD4 = refStock.d4Date || '--';
const refD5 = refStock.d5Date || '--';
const refD6 = refStock.d6Date || '--';
const refD7 = refStock.d7Date || '--';

let mode4HeaderHtml = '';
let theadHtml = '';

if (timeMode === 'mode4') {
const avgD1 = countD1 > 0 ? (sumD1 / countD1).toFixed(2) : "0.00";
const avgD2 = countD2 > 0 ? (sumD2 / countD2).toFixed(2) : "0.00";
const avgD3 = countD3 > 0 ? (sumD3 / countD3).toFixed(2) : "0.00";
const avgD4 = countD4 > 0 ? (sumD4 / countD4).toFixed(2) : "0.00";
const avgD5 = countD5 > 0 ? (sumD5 / countD5).toFixed(2) : "0.00";
const avgD6 = countD6 > 0 ? (sumD6 / countD6).toFixed(2) : "0.00";
const avgD7 = countD7 > 0 ? (sumD7 / countD7).toFixed(2) : "0.00";

mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-6 text-sm items-center flex-wrap justify-end w-full lg:w-auto mt-2 lg:mt-0">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center"><span class="text-slate-400 text-xs uppercase mb-1">有效股票</span><span class="text-white font-mono text-base font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+0</span><span class="font-mono text-sm font-bold my-0.5 \${avgD1 > 0 ? 'text-red-500' : avgD1 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD1 > 0 ? '+' : ''}\${avgD1}%</span><span class="text-blue-300 text-xs">(\${refD1})</span></div>\`;
if (maxDays >= 2) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+1</span><span class="font-mono text-sm font-bold my-0.5 \${avgD2 > 0 ? 'text-red-500' : avgD2 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD2 > 0 ? '+' : ''}\${avgD2}%</span><span class="text-blue-300 text-xs">(\${refD2})</span></div>\`;
if (maxDays >= 3) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+2</span><span class="font-mono text-sm font-bold my-0.5 \${avgD3 > 0 ? 'text-red-500' : avgD3 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD3 > 0 ? '+' : ''}\${avgD3}%</span><span class="text-blue-300 text-xs">(\${refD3})</span></div>\`;
if (maxDays >= 4) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+3</span><span class="font-mono text-sm font-bold my-0.5 \${avgD4 > 0 ? 'text-red-500' : avgD4 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD4 > 0 ? '+' : ''}\${avgD4}%</span><span class="text-blue-300 text-xs">(\${refD4})</span></div>\`;
if (maxDays >= 5) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+4</span><span class="font-mono text-sm font-bold my-0.5 \${avgD5 > 0 ? 'text-red-500' : avgD5 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD5 > 0 ? '+' : ''}\${avgD5}%</span><span class="text-blue-300 text-xs">(\${refD5})</span></div>\`;
if (maxDays >= 6) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+5</span><span class="font-mono text-sm font-bold my-0.5 \${avgD6 > 0 ? 'text-red-500' : avgD6 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD6 > 0 ? '+' : ''}\${avgD6}%</span><span class="text-blue-300 text-xs">(\${refD6})</span></div>\`;
if (maxDays >= 7) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+6</span><span class="font-mono text-sm font-bold my-0.5 \${avgD7 > 0 ? 'text-red-500' : avgD7 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD7 > 0 ? '+' : ''}\${avgD7}%</span><span class="text-blue-300 text-xs">(\${refD7})</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4"><span class="text-purple-400 text-xs uppercase font-bold mb-1">累计总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-lg">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">预警价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+0 (当日)</th>\`;
if (maxDays >= 2) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+1 (次日)</th>\`;
if (maxDays >= 3) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+2 (三日)</th>\`;
if (maxDays >= 4) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+3 (四日)</th>\`;
if (maxDays >= 5) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+4 (五日)</th>\`;
if (maxDays >= 6) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+5 (六日)</th>\`;
if (maxDays >= 7) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+6 (七日)</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right text-purple-300 whitespace-nowrap">累计盈亏</th>\`;
} else {
mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-8 text-sm items-center">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">有效股票数</span><span class="text-white font-mono font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">胜率</span><span class="text-white font-mono font-bold">\${winRate}%</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">策略总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-base">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">文档买入价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">结算收盘价 <span class="text-[9px] text-slate-500 normal-case tracking-normal">(取值日期)</span></th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">单只盈亏比</th>\`;
}

let tbodyHtml = '';
list.forEach(i => {
const pColor = i.profitRatio > 0 ? 'text-red-500' : i.profitRatio < 0 ? 'text-green-500' : 'text-slate-400';
const statusTag = i.error ? '<span class="px-2 py-1 rounded bg-slate-500/30 text-slate-400 border border-slate-500/50 whitespace-nowrap">未收录</span>' :
i.isWin ? '<span class="px-2 py-1 rounded bg-red-500/10 text-red-500 border border-red-500/20 whitespace-nowrap">盈利</span>' :
i.isTie ? '<span class="px-2 py-1 rounded bg-slate-500/10 text-slate-400 border border-slate-500/20 whitespace-nowrap">平盘</span>' :
'<span class="px-2 py-1 rounded bg-green-500/10 text-green-500 border border-green-500/20 whitespace-nowrap">亏损</span>';

let rowInnerHtml = '';
if (timeMode === 'mode4') {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap align-middle">\${i.price.toFixed(2)}</td>\`;

if (i.error) {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 2) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 3) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 4) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 5) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 6) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 7) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
} else {
const c1 = i.d1Profit > 0 ? 'text-red-500' : i.d1Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d1Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c1} py-0.5">\${(i.d1Profit>0?'+':'')}\${i.d1Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d1Date})</div>
</td>\`;

if (maxDays >= 2) {
if (i.d2Close) {
const c2 = i.d2Profit > 0 ? 'text-red-500' : i.d2Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d2Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c2} py-0.5">\${(i.d2Profit>0?'+':'')}\${i.d2Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d2Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 3) {
if (i.d3Close) {
const c3 = i.d3Profit > 0 ? 'text-red-500' : i.d3Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d3Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c3} py-0.5">\${(i.d3Profit>0?'+':'')}\${i.d3Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d3Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 4) {
if (i.d4Close) {
const c4 = i.d4Profit > 0 ? 'text-red-500' : i.d4Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d4Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c4} py-0.5">\${(i.d4Profit>0?'+':'')}\${i.d4Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d4Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 5) {
if (i.d5Close) {
const c5 = i.d5Profit > 0 ? 'text-red-500' : i.d5Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d5Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c5} py-0.5">\${(i.d5Profit>0?'+':'')}\${i.d5Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d5Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 6) {
if (i.d6Close) {
const c6 = i.d6Profit > 0 ? 'text-red-500' : i.d6Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d6Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c6} py-0.5">\${(i.d6Profit>0?'+':'')}\${i.d6Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d6Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 7) {
if (i.d7Close) {
const c7 = i.d7Profit > 0 ? 'text-red-500' : i.d7Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d7Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c7} py-0.5">\${(i.d7Profit>0?'+':'')}\${i.d7Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d7Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
}
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} text-sm whitespace-nowrap align-middle">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap">\${i.price.toFixed(2)}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono text-slate-300 whitespace-nowrap">\${i.error ? '--' : \`\${i.closePrice.toFixed(2)} <br><span class="text-[10px] text-slate-500 font-bold">(\${i.matchedDate})</span>\`}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} whitespace-nowrap">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
}

tbodyHtml += \`
<tr class="hover:bg-slate-800/60 transition-colors \${i.error ? 'opacity-40' : ''}">
<td class="p-4 align-middle">
<div class="text-blue-400 font-bold whitespace-nowrap">\${i.code}</div>
<div class="text-slate-300 whitespace-nowrap flex items-center gap-1">
\${i.name}
<span class="text-[10px] text-slate-600 opacity-50 font-normal cursor-default select-none">\${i.provider || ''}</span>
</div>
</td>
<td class="p-4 text-slate-400 font-mono whitespace-nowrap align-middle">\${i.date} \${i.time}</td>
\${rowInnerHtml}
<td class="p-4 text-center text-[10px] font-bold align-middle">\${statusTag}</td>
</tr>
\`;
});

const groupHtml = \`
<div class="card overflow-hidden shadow-xl animate-row border border-slate-700 w-full">
<div class="group-header bg-slate-800 p-4 border-b border-slate-700 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4" onclick="toggleAccordion('body-\${groupId}')">
<div class="flex items-center gap-3">
<i class="fa-solid fa-chevron-down chevron-icon text-slate-400"></i>
<span class="bg-indigo-600/30 text-indigo-300 text-xs px-2 py-1 rounded border border-indigo-500/30 font-bold truncate max-w-[200px]" title="\${strategyName}">
\${strategyName}
</span>
\${totalValidCount < list.length ? \`<span class="text-[10px] bg-red-900/40 text-red-400 px-2 py-0.5 rounded border border-red-800/50">屏蔽 \${list.length - totalValidCount} 支无数据</span>\` : ''}
</div>
\${mode4HeaderHtml}
</div>

<div id="body-\${groupId}" class="strategy-body hidden overflow-x-auto bg-[#172033]">
<table class="w-full text-xs text-left">
<thead class="text-slate-400 bg-slate-900/50 uppercase">
<tr>
<th class="p-4 font-medium whitespace-nowrap">股票信息</th>
<th class="p-4 font-medium whitespace-nowrap">预警时间</th>
\${theadHtml}
<th class="p-4 font-medium text-center whitespace-nowrap">状态</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-800/50">
\${tbodyHtml}
</tbody>
</table>
</div>
</div>
\`;
container.insertAdjacentHTML('beforeend', groupHtml);

list.strategyTotalProfitRatio = strategyTotalProfitRatio;
list.validCount = totalValidCount;
}

document.getElementById('screenshotBtn').addEventListener('click', async function() {
const btn = this;
const originalHTML = btn.innerHTML;
const resultsDiv = document.getElementById('results');

btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> 生成图中...';
btn.disabled = true;

try {
const canvas = await html2canvas(resultsDiv, {
backgroundColor: '#0f172a',
scale: 3,
useCORS: true,
logging: false,
allowTaint: true
});

const imgData = canvas.toDataURL('image/png', 1.0);
const link = document.createElement('a');
link.href = imgData;
link.download = getDynamicFileName('png');
link.click();
} catch (err) {
alert("生成图片失败: " + err.message);
} finally {
btn.innerHTML = originalHTML;
btn.disabled = false;
}
});

document.getElementById('exportBtn').onclick = () => {
let csv = "";

finalData.forEach(group => {
const timeMode = group.timeMode;
const maxD = timeMode === 'mode4' ? Math.max(1, ...group.items.filter(i=>!i.error).map(s=>s.daysAvailable||1)) : 1;

if (timeMode === 'mode4') {
csv += "\\ufeff预警时间,股票代码,股票名称,文档预警价,T+0取值日期,T+0收盘价,T+0单日盈亏";
if (maxD >= 2) csv += ",T+1取值日期,T+1收盘价,T+1单日盈亏";
if (maxD >= 3) csv += ",T+2取值日期,T+2收盘价,T+2单日盈亏";
if (maxD >= 4) csv += ",T+3取值日期,T+3收盘价,T+3单日盈亏";
if (maxD >= 5) csv += ",T+4取值日期,T+4收盘价,T+4单日盈亏";
if (maxD >= 6) csv += ",T+5取值日期,T+5收盘价,T+5单日盈亏";
if (maxD >= 7) csv += ",T+6取值日期,T+6收盘价,T+6单日盈亏";
csv += ",累计总盈亏,状态,策略名称\\n";
} else {
csv += "\\ufeff预警时间,股票代码,股票名称,文档买入基准,结算收盘价,取价日期,单只盈亏比,状态,策略名称\\n";
}

group.items.forEach(s => {
const status = s.error ? "未收录" : (s.isWin ? "盈利" : s.isTie ? "平盘" : "亏损");

if (timeMode === 'mode4') {
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\`;
csv += \`"\${s.error ? '--' : s.d1Date}",\${s.error ? 0 : s.d1Close.toFixed(2)},\${s.error ? 0 : s.d1Profit.toFixed(2)}%,\`;
if (maxD >= 2) csv += \`"\${s.d2Date||'--'}",\${s.d2Close ? s.d2Close.toFixed(2) : '--'},\${s.d2Profit !== null ? s.d2Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 3) csv += \`"\${s.d3Date||'--'}",\${s.d3Close ? s.d3Close.toFixed(2) : '--'},\${s.d3Profit !== null ? s.d3Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 4) csv += \`"\${s.d4Date||'--'}",\${s.d4Close ? s.d4Close.toFixed(2) : '--'},\${s.d4Profit !== null ? s.d4Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 5) csv += \`"\${s.d5Date||'--'}",\${s.d5Close ? s.d5Close.toFixed(2) : '--'},\${s.d5Profit !== null ? s.d5Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 6) csv += \`"\${s.d6Date||'--'}",\${s.d6Close ? s.d6Close.toFixed(2) : '--'},\${s.d6Profit !== null ? s.d6Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 7) csv += \`"\${s.d7Date||'--'}",\${s.d7Close ? s.d7Close.toFixed(2) : '--'},\${s.d7Profit !== null ? s.d7Profit.toFixed(2) + '%' : '--'},\`;
csv += \`\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
} else {
const mDate = s.error ? "--" : s.matchedDate;
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\${s.error ? 0 : s.closePrice.toFixed(2)},"\${mDate}",\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
}
});

csv += \`"统计信息","有效股票数量:\${group.items.validCount}",,,,,"策略总盈亏:",\${group.items.strategyTotalProfitRatio}%,,"\${group.strategy} 汇总"\\n\\n\`;
});

const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = getDynamicFileName('csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
</script>
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html;charset=UTF-8" } });
}
};

修复打赏弹窗

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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
export default {
async fetch(request) {
const url = new URL(request.url);
// ==========================================
// 代理路由:保持 3 级容错分发不变
// ==========================================
if (url.pathname === "/api/kline") {
const code = url.searchParams.get("code");
const prefix = url.searchParams.get("prefix");
const provider = url.searchParams.get("provider");

let targetUrl = "";

if (provider === "em") {
const secid = (prefix === "sh" ? "1." : "0.") + code;
targetUrl = `https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${secid}&klt=101&fqt=1&end=20500000&lmt=320&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61`;
} else if (provider === "sina") {
targetUrl = `https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketData.getKLineData?symbol=${prefix}${code}&scale=240&ma=no&datalen=320`;
} else {
targetUrl = `https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=${prefix}${code},day,,,320,qfq`;
}

try {
const fetchRes = await fetch(targetUrl, {
headers: { "User-Agent": "Mozilla/5.0" }
});
const data = await fetchRes.arrayBuffer();

return new Response(data, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
},
});
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500, headers: { "Access-Control-Allow-Origin": "*" } });
}
}
// ==========================================
// 前端 HTML 界面
// ==========================================
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>量化策略回测终端</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
:root { --up: #ef4444; --down: #22c55e; --bg-main: #0f172a; --bg-card: #1e293b; }
body { background-color: var(--bg-main); color: #f1f5f9; font-family: 'Inter', system-ui, sans-serif; }
.card { background: var(--bg-card); border: 1px solid #334155; border-radius: 1rem; }
.input-dark { background: #0f172a; border: 1px solid #475569; color: #38bdf8; font-weight: 700; padding: 0.5rem; border-radius: 0.5rem; color-scheme: dark; transition: all 0.2s ease;}
.input-dark:focus { border-color: #3b82f6; outline: none; box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3); }
.btn-primary { background: #2563eb; transition: all 0.2s; }
.btn-primary:hover { background: #3b82f6; transform: translateY(-1px); }
.btn-primary:disabled { background: #64748b; cursor: not-allowed; }
.btn-warning { background: #ea580c; transition: all 0.2s; }
.btn-warning:hover { background: #f97316; transform: translateY(-1px); }
.radio-custom:checked + div { border-color: #3b82f6; background: rgba(59, 130, 246, 0.1); }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.animate-row { animation: fadeIn 0.3s ease-out forwards; }
.group-header { cursor: pointer; user-select: none; transition: background-color 0.2s; }
.group-header:hover { background-color: #334155; }
.chevron-icon { transition: transform 0.3s ease; }
.group-open .chevron-icon { transform: rotate(180deg); }

/* 新增:底部打赏栏样式(备案式极简布局) */
.reward-footer-bar {
border-top: 1px solid #334155;
padding: 1.5rem 1rem;
text-align: center;
}
.reward-footer-text {
color: #94a3b8;
font-size: 0.875rem;
margin-bottom: 1rem;
line-height: 1.5;
max-width: 800px;
margin-left: auto;
margin-right: auto;
}
.reward-footer-btns {
display: flex;
gap: 1rem;
justify-content: center;
flex-wrap: wrap;
}
.reward-footer-btn {
padding: 0.5rem 1.25rem;
border-radius: 0.5rem;
font-weight: 600;
font-size: 0.875rem;
transition: all 0.2s ease;
border: 1px solid transparent;
display: inline-flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
}
.reward-btn-alipay {
background: rgba(37, 99, 235, 0.1);
border-color: #2563eb;
color: #3b82f6;
}
.reward-btn-alipay:hover {
background: #2563eb;
color: white;
transform: translateY(-1px);
box-shadow: 0 0 12px rgba(37, 99, 235, 0.4);
}
.reward-btn-wechat {
background: rgba(22, 163, 74, 0.1);
border-color: #16a34a;
color: #22c55e;
}
.reward-btn-wechat:hover {
background: #16a34a;
color: white;
transform: translateY(-1px);
box-shadow: 0 0 12px rgba(22, 163, 74, 0.4);
}

/* 新增:打赏弹窗样式 */
.reward-modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
animation: fadeIn 0.2s ease-out;
}
.reward-modal-content {
background: #1e293b;
border: 1px solid #475569;
border-radius: 1rem;
padding: 1.5rem;
max-width: 320px;
width: 100%;
animation: fadeIn 0.3s ease-out;
}
.reward-modal-title {
text-align: center;
font-size: 1rem;
font-weight: 700;
color: #f1f5f9;
margin-bottom: 1rem;
}
.reward-modal-img {
width: 100%;
height: auto;
border-radius: 0.5rem;
margin-bottom: 0.75rem;
}
.reward-modal-tip {
text-align: center;
font-size: 0.75rem;
color: #94a3b8;
}
</style>
</head>
<body class="min-h-screen p-4 md:p-8">
<div class="max-w-[1400px] mx-auto space-y-6">

<div class="card p-6 shadow-2xl w-full">
<div class="flex flex-wrap items-center justify-between gap-4 border-b border-slate-700 pb-4">
<div class="flex items-center gap-4">
<div class="bg-blue-600 p-4 rounded-xl shadow-[0_0_15px_rgba(37,99,235,0.6)]"><i class="fa-solid fa-chart-line text-2xl text-white"></i></div>
<div class="flex flex-col gap-2">
<h1 class="text-2xl font-bold tracking-tight text-white flex items-center gap-3 flex-wrap">
策略预警回测终端
<span class="bg-blue-600/90 hover:bg-blue-500 transition-colors text-white text-sm px-3 py-1 rounded-md shadow-[0_0_12px_rgba(37,99,235,0.8)] font-bold tracking-widest flex items-center gap-1.5 border border-blue-400 cursor-default">
<i class="fa-brands fa-qq text-lg"></i> 股票QQ交流群: 643618300
</span>
</h1>
</div>
</div>
<div class="flex gap-3">
<input type="file" id="fileInput" class="hidden" accept=".txt">
<button id="importBtn" onclick="document.getElementById('fileInput').click()" class="bg-slate-700 hover:bg-slate-600 px-5 py-2.5 rounded-lg border border-slate-500 transition-colors font-medium shadow-md">
<i class="fa-solid fa-file-import mr-2"></i>上传数据 (TXT)
</button>
<button id="runBtn" disabled class="btn-primary px-6 py-2.5 rounded-lg font-bold shadow-lg shadow-blue-900/50">
<i class="fa-solid fa-play mr-2"></i>开始回测
</button>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 pt-6">
<div class="space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-blue-500 pl-2">查询与筛选</h3>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">数量 (空/0查全部):</label>
<input type="number" id="limitCount" placeholder="全部" min="0" class="input-dark w-24 text-center text-sm shadow-inner">
</div>
<div class="flex items-center justify-between">
<label class="text-xs text-slate-400">预警时段 (过滤):</label>
<div class="flex items-center gap-1">
<input type="time" id="startTime" class="input-dark text-xs p-1 shadow-inner">
<span class="text-slate-500 font-bold">-</span>
<input type="time" id="endTime" class="input-dark text-xs p-1 shadow-inner">
</div>
</div>
</div>
<div class="md:col-span-3 space-y-3">
<h3 class="text-sm font-bold text-slate-300 border-l-2 border-purple-500 pl-2">结算价提取基准</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode1" checked class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">① 预警当日</div>
<div class="text-[10px] text-slate-400 leading-tight">提取预警当天的收盘价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode2" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">② 最新实时</div>
<div class="text-[10px] text-slate-400 leading-tight">提取股票当下的最新价</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode3" class="peer hidden radio-custom">
<div class="border border-slate-600 rounded-lg p-3 hover:border-blue-400 transition-colors h-full flex flex-col justify-center bg-slate-800/50 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-white mb-1">③ 单日偏移</div>
<div id="customDaysUi" class="flex gap-2 opacity-30 pointer-events-none transition-opacity">
<div class="flex items-center gap-1">
<span class="text-[10px]">向后偏移</span>
<input type="number" id="nextDays" value="1" min="1" max="20" class="input-dark w-12 p-1 text-center text-xs">
<span class="text-[10px]">个交易日</span>
</div>
</div>
</div>
</label>
<label class="cursor-pointer relative">
<input type="radio" name="timeMode" value="mode4" class="peer hidden radio-custom">
<div class="border border-purple-600 rounded-lg p-3 hover:border-purple-400 transition-colors h-full flex flex-col justify-center bg-purple-900/20 shadow-inner min-h-[72px]">
<div class="font-bold text-sm text-purple-300 mb-1">④ 连续七日追踪</div>
<div class="text-[10px] text-slate-400 leading-tight">T+0至T+6每日独立涨跌</div>
</div>
</label>
</div>
</div>
</div>
</div>
<div id="progressBox" class="hidden card p-6 border border-blue-900 shadow-[0_0_15px_rgba(59,130,246,0.1)] w-full">
<div class="flex justify-between items-center text-xs mb-2 text-blue-300">
<div class="flex items-center gap-2">
<span id="progressText" class="font-medium">初始化引擎中...</span>
<span id="sourceBadge" class="hidden px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-all duration-200"></span>
</div>
<span id="progressPercent" class="font-mono font-bold">0%</span>
</div>
<div class="w-full bg-slate-800 rounded-full h-2">
<div id="progressBar" class="bg-gradient-to-r from-blue-600 to-blue-400 h-2 rounded-full transition-all duration-300 shadow-[0_0_10px_rgba(59,130,246,0.8)]" style="width: 0%"></div>
</div>
</div>
<div id="results" class="space-y-6 pb-10 w-full">
<div class="text-center py-20 text-slate-600 border-2 border-dashed border-slate-700 rounded-2xl bg-slate-800/50">
<i class="fa-solid fa-inbox text-5xl mb-4 opacity-50"></i>
<p class="text-sm">尚未导入数据。请上传包含预警信息的 TXT 文件。</p>
</div>
</div>

<!-- 新增:底部打赏栏 - 备案式极简布局 -->
<div class="reward-footer-bar">
<p class="reward-footer-text">本站所有内容免费分享,若对你有所帮助,可随意打赏一杯咖啡,让我有动力持续维护与更新。</p>
<div class="reward-footer-btns">
<button id="alipayBtn" class="reward-footer-btn reward-btn-alipay">
<i class="fa-brands fa-alipay"></i> 支付宝打赏
</button>
<button id="wechatBtn" class="reward-footer-btn reward-btn-wechat">
<i class="fa-brands fa-weixin"></i> 微信打赏
</button>
</div>
</div>
</div>

<!-- 新增:打赏弹窗 - 默认隐藏 -->
<div id="rewardModal" class="hidden">
<div class="reward-modal-overlay" id="modalOverlay">
<div class="reward-modal-content" id="modalContent">
<h3 id="modalTitle" class="reward-modal-title">支付宝打赏</h3>
<img id="modalImg" class="reward-modal-img" src="" alt="收款码" loading="lazy" />
<p class="reward-modal-tip">点击空白区域关闭弹窗</p>
</div>
</div>
</div>

<div id="actionButtons" class="hidden fixed bottom-8 right-8 z-50 flex flex-col gap-3">
<button id="screenshotBtn" class="bg-indigo-600 hover:bg-indigo-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(79,70,229,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-camera"></i> 保存长图
</button>
<button id="exportBtn" class="bg-emerald-600 hover:bg-emerald-500 text-white px-6 py-3 rounded-full shadow-[0_10px_25px_rgba(16,185,129,0.4)] transition-all transform hover:scale-105 font-bold flex items-center justify-center gap-2">
<i class="fa-solid fa-file-excel"></i> 导出 CSV
</button>
</div>
<script>
const API_URL = "/api/kline";

let rawContent = "";
let finalData = [];
let globalRunId = 0;
let currentRunMode = "";
function getDynamicFileName(extension) {
const limit = document.getElementById('limitCount').value;
const limitStr = (!limit || parseInt(limit) === 0) ? "全部" : limit + "只";
const st = document.getElementById('startTime').value || "09:30";
const et = document.getElementById('endTime').value || "15:00";
const timeStr = st.replace(':', '') + "-" + et.replace(':', '');
let modeStr = "";
if (currentRunMode === 'mode1') modeStr = "当日";
else if (currentRunMode === 'mode2') modeStr = "实时";
else if (currentRunMode === 'mode3') modeStr = "偏移";
else if (currentRunMode === 'mode4') modeStr = "连续追踪";

const dateStr = new Date().toLocaleDateString().replace(/\\//g, '');
return \`量化复盘_[\${limitStr}]_[\${timeStr}]_[\${modeStr}]_\${dateStr}.\${extension}\`;
}
document.querySelectorAll('input[name="timeMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const customUi = document.getElementById('customDaysUi');
if (e.target.value === 'mode3') customUi.classList.remove('opacity-30', 'pointer-events-none');
else customUi.classList.add('opacity-30', 'pointer-events-none');
});
});
document.getElementById('fileInput').addEventListener('change', function(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
const uint8 = new Uint8Array(event.target.result);
rawContent = new TextDecoder('gb18030').decode(uint8);
document.getElementById('runBtn').disabled = false;
document.getElementById('importBtn').innerHTML = '<i class="fa-solid fa-check mr-2 text-emerald-400"></i>文件已就绪 (' + file.name + ')';
};
reader.readAsArrayBuffer(file);
});
const delay = ms => new Promise(res => setTimeout(res, ms));
document.getElementById('runBtn').addEventListener('click', async function() {
globalRunId++;
const currentRunId = globalRunId;
const resultsDiv = document.getElementById('results');
const progressBox = document.getElementById('progressBox');
const runBtn = this;

resultsDiv.innerHTML = "";
finalData = [];
progressBox.classList.remove('hidden');
document.getElementById('actionButtons').classList.add('hidden');
runBtn.innerHTML = '<i class="fa-solid fa-rotate-right fa-spin mr-2"></i>中断重试';
runBtn.classList.remove('btn-primary');
runBtn.classList.add('btn-warning');
const limit = parseInt(document.getElementById('limitCount').value) || 999999;
const startTime = document.getElementById('startTime').value;
const endTime = document.getElementById('endTime').value;
const timeMode = document.querySelector('input[name="timeMode"]:checked').value;
currentRunMode = timeMode;
const nextDays = parseInt(document.getElementById('nextDays').value) || 0;
const lines = rawContent.split(/\\r?\\n/);
let strategyMap = new Map();
lines.forEach(line => {
const rawParts = line.trim().split(/\\t|\\s{2,}/);
const parts = rawParts.filter(p => p.trim() !== '');
if (parts.length < 5) return;
const code = parts[0].trim();
const name = parts[1].trim();
let dateIdx = -1;
for(let j = 2; j < parts.length; j++) {
if(parts[j].match(/^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}/)) {
dateIdx = j;
break;
}
}
if (dateIdx === -1) return;
let dateTimeStr = parts[dateIdx].trim();
let date, time, priceIdx;
if (dateTimeStr.includes(' ')) {
let dtParts = dateTimeStr.split(/\\s+/);
date = dtParts[0];
time = dtParts[1] || "15:00";
priceIdx = dateIdx + 1;
} else {
date = parts[dateIdx].trim();
time = parts[dateIdx+1].trim();
priceIdx = dateIdx + 2;
}
const price = parseFloat(parts[priceIdx]);
if(isNaN(price)) return;
const strategy = parts[parts.length - 1].trim();
if (startTime && time < startTime) return;
if (endTime && time > endTime) return;
if (!strategyMap.has(strategy)) strategyMap.set(strategy, []);
strategyMap.get(strategy).push({ code, name, date, time, price, strategy });
});
const strategies = Array.from(strategyMap.keys());
if(strategies.length === 0) {
alert("未解析到符合条件的数据,请检查格式或时间过滤段!");
resetButton(runBtn);
progressBox.classList.add('hidden');
return;
}
let processedCount = 0;
const totalToProcess = Array.from(strategyMap.values()).reduce((sum, arr) => sum + Math.min(arr.length, limit), 0);
let groupIndex = 0;
for (const sName of strategies) {
if (currentRunId !== globalRunId) return;
let group = strategyMap.get(sName);
group.sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time));
group = group.slice(0, limit);
const processedGroup = [];
for (let i = 0; i < group.length; i += 5) {
if (currentRunId !== globalRunId) return;

const chunk = group.slice(i, i + 5);
const chunkRes = await Promise.all(chunk.map(async item => {
const result = await fetchAndCalculate(item, timeMode, nextDays);
processedCount++;
if (currentRunId === globalRunId) {
updateProgress(processedCount, totalToProcess, \`查询分析中 [\${sName}]: \${item.name}\`, result.provider);
}
return result;
}));

if (currentRunId !== globalRunId) return;
processedGroup.push(...chunkRes);
await delay(50);
}
if (currentRunId !== globalRunId) return;
renderStrategyGroup(sName, processedGroup, groupIndex++, timeMode);
finalData.push({ strategy: sName, items: processedGroup, timeMode });
}
if (currentRunId === globalRunId) {
resetButton(runBtn);
updateProgress(100, 100, "分析计算完成!");
document.getElementById('actionButtons').classList.remove('hidden');
}
});
function resetButton(btn) {
btn.innerHTML = '<i class="fa-solid fa-play mr-2"></i>开始回测';
btn.classList.remove('btn-warning');
btn.classList.add('btn-primary');
}
function updateProgress(cur, total, text, provider) {
const p = total === 0 ? 100 : Math.floor((cur / total) * 100);
document.getElementById('progressBar').style.width = p + "%";
document.getElementById('progressPercent').innerText = p + "%";
document.getElementById('progressText').innerText = text;
const badge = document.getElementById('sourceBadge');
if (p >= 100) {
badge.classList.add('hidden');
} else if (provider && provider !== '无') {
badge.classList.remove('hidden');
badge.innerText = provider;
badge.className = "px-1.5 py-0.5 rounded-[4px] text-[10px] font-black text-white shadow-md transition-colors ";
if (provider === '东') badge.className += "bg-red-500/80";
else if (provider === '腾') badge.className += "bg-blue-500/80";
else if (provider === '新') badge.className += "bg-yellow-600/80";
}
}
const toYYYYMMDD = (dStr) => {
const matches = String(dStr).match(/(\\d{4})[-/]?(\\d{1,2})[-/]?(\\d{1,2})/);
if (matches) {
return matches[1] + matches[2].padStart(2, '0') + matches[3].padStart(2, '0');
}
return String(dStr).replace(/\\D/g, '');
};
async function fetchAndCalculate(stock, mode, next) {
const getPrefix = (c) => {
if (c.startsWith('60') || c.startsWith('68')) return 'sh';
if (c.startsWith('00') || c.startsWith('30')) return 'sz';
if (c.startsWith('8') || c.startsWith('43') || c.startsWith('92') || c.startsWith('87')) return 'bj';
return 'sz';
};
const prefix = getPrefix(stock.code);
const fullCode = prefix + stock.code;

const fetchEM = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=em&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.data && json.data.klines && json.data.klines.length > 0) {
const kData = json.data.klines.map(line => {
const parts = line.split(',');
return [parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]];
});
return { kData, provider: '东' };
}
throw new Error("EM None");
};
const fetchTX = async () => {
if (prefix === 'bj') throw new Error("TX skip BJ");
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=tx&_=\${Date.now()}\`);
const json = await res.json();
let kData = json.data[fullCode]?.qfqday || json.data[fullCode]?.day;
if (kData && kData.length > 0) {
const qtData = json.data[fullCode].qt?.[fullCode];
if (qtData) {
const qtDateStr = qtData[30].substring(0, 8);
const formattedQtDate = qtDateStr.substring(0,4) + "-" + qtDateStr.substring(4,6) + "-" + qtDateStr.substring(6,8);
const currentPrice = parseFloat(qtData[3]);
if (kData[kData.length - 1][0] !== formattedQtDate && currentPrice > 0) {
kData.push([formattedQtDate, qtData[5], qtData[3], qtData[33], qtData[34], qtData[36]]);
}
}
return { kData, provider: '腾' };
}
throw new Error("TX None");
};
const fetchSina = async () => {
const res = await fetch(\`\${API_URL}?code=\${stock.code}&prefix=\${prefix}&provider=sina&_=\${Date.now()}\`);
const json = await res.json();
if (json && json.length > 0) {
const kData = json.map(item => [item.day.split(' ')[0], item.open, item.close, item.high, item.low, item.volume]);
return { kData, provider: '新' };
}
throw new Error("Sina None");
};
const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const bjTime = new Date(utc + (3600000 * 8));
const h = bjTime.getHours();
const m = bjTime.getMinutes();
const timeVal = h * 100 + m;

const isTradingTime = timeVal >= 915 && timeVal < 1500;

let fetchResult = null;
try {
if (isTradingTime) {
try { fetchResult = await fetchEM(); }
catch (e1) {
try { fetchResult = await fetchTX(); }
catch (e2) { fetchResult = await fetchSina(); }
}
} else {
fetchResult = await new Promise((resolve, reject) => {
let errCount = 0;
const checkReject = () => { errCount++; if (errCount === 3) reject(new Error("All APIs failed")); };
fetchEM().then(resolve).catch(checkReject);
fetchTX().then(resolve).catch(checkReject);
fetchSina().then(resolve).catch(checkReject);
});
}
const { kData, provider } = fetchResult;
const normBaseDate = toYYYYMMDD(stock.date);

let baseIdx = -1;
if (mode !== 'mode2') {
for (let i = 0; i < kData.length; i++) {
if (toYYYYMMDD(kData[i][0]) === normBaseDate) {
baseIdx = i; break;
}
}
if (baseIdx === -1) {
for (let i = kData.length - 1; i >= 0; i--) {
if (toYYYYMMDD(kData[i][0]) < normBaseDate) {
baseIdx = i; break;
}
}
}
if (baseIdx === -1) throw new Error("Date Out of Range");
}
const alertPrice = stock.price;
if (mode === 'mode4') {
const day1 = kData[baseIdx];
const day2 = baseIdx + 1 < kData.length ? kData[baseIdx + 1] : null;
const day3 = baseIdx + 2 < kData.length ? kData[baseIdx + 2] : null;
const day4 = baseIdx + 3 < kData.length ? kData[baseIdx + 3] : null;
const day5 = baseIdx + 4 < kData.length ? kData[baseIdx + 4] : null;
const day6 = baseIdx + 5 < kData.length ? kData[baseIdx + 5] : null;
const day7 = baseIdx + 6 < kData.length ? kData[baseIdx + 6] : null;
const d1Close = parseFloat(day1[2]);
const d1Profit = ((d1Close - alertPrice) / alertPrice) * 100;
let d2Close = null, d2Profit = null;
if (day2) { d2Close = parseFloat(day2[2]); d2Profit = ((d2Close - d1Close) / d1Close) * 100; }
let d3Close = null, d3Profit = null;
if (day3) { d3Close = parseFloat(day3[2]); d3Profit = ((d3Close - d2Close) / d2Close) * 100; }
let d4Close = null, d4Profit = null;
if (day4) { d4Close = parseFloat(day4[2]); d4Profit = ((d4Close - d3Close) / d3Close) * 100; }
let d5Close = null, d5Profit = null;
if (day5) { d5Close = parseFloat(day5[2]); d5Profit = ((d5Close - d4Close) / d4Close) * 100; }
let d6Close = null, d6Profit = null;
if (day6) { d6Close = parseFloat(day6[2]); d6Profit = ((d6Close - d5Close) / d5Close) * 100; }
let d7Close = null, d7Profit = null;
if (day7) { d7Close = parseFloat(day7[2]); d7Profit = ((d7Close - d6Close) / d6Close) * 100; }
const finalClose = d7Close || d6Close || d5Close || d4Close || d3Close || d2Close || d1Close;
const totalProfit = ((finalClose - alertPrice) / alertPrice) * 100;
const daysAvailable = 1 + (day2 ? 1 : 0) + (day3 ? 1 : 0) + (day4 ? 1 : 0) + (day5 ? 1 : 0) + (day6 ? 1 : 0) + (day7 ? 1 : 0);
return {
...stock,
d1Close, d1Profit, d1Date: day1[0].substring(5),
d2Close, d2Profit, d2Date: day2 ? day2[0].substring(5) : null,
d3Close, d3Profit, d3Date: day3 ? day3[0].substring(5) : null,
d4Close, d4Profit, d4Date: day4 ? day4[0].substring(5) : null,
d5Close, d5Profit, d5Date: day5 ? day5[0].substring(5) : null,
d6Close, d6Profit, d6Date: day6 ? day6[0].substring(5) : null,
d7Close, d7Profit, d7Date: day7 ? day7[0].substring(5) : null,
closePrice: finalClose,
profitRatio: totalProfit,
isWin: totalProfit > 0,
isTie: totalProfit === 0,
matchedDate: (day7 || day6 || day5 || day4 || day3 || day2 || day1)[0].substring(5),
daysAvailable: daysAvailable,
error: false,
provider: provider
};
}

let targetIdx = -1;
if (mode === 'mode2') targetIdx = kData.length - 1;
else if (mode === 'mode1') targetIdx = baseIdx;
else if (mode === 'mode3') {
targetIdx = baseIdx + next;
if (targetIdx >= kData.length) throw new Error("Target Future Date Not Exists");
}

if (targetIdx < 0) targetIdx = 0;
const closePrice = parseFloat(kData[targetIdx][2]);
const matchedDateStr = kData[targetIdx][0].substring(5);

const profitDiff = closePrice - alertPrice;
const profitRatio = (profitDiff / alertPrice) * 100;
return {
...stock,
closePrice: closePrice,
profitRatio: profitRatio,
isWin: profitDiff > 0,
isTie: profitDiff === 0,
matchedDate: matchedDateStr,
error: false,
provider: provider
};
} catch (e) {
return { ...stock, closePrice: stock.price, profitRatio: 0, isWin: false, isTie: false, error: true, daysAvailable: 0, provider: '无' };
}
}
window.toggleAccordion = function(id) {
const allBodies = document.querySelectorAll('.strategy-body');
allBodies.forEach(body => {
if (body.id === id) {
body.classList.toggle('hidden');
body.previousElementSibling.classList.toggle('group-open');
} else {
body.classList.add('hidden');
body.previousElementSibling.classList.remove('group-open');
}
});
};
function renderStrategyGroup(strategyName, list, groupId, timeMode) {
const container = document.getElementById('results');
const validStocks = list.filter(i => !i.error);
const totalValidCount = validStocks.length;

let totalProfitRatioSum = 0;
let winCount = 0;

let sumD1 = 0, countD1 = 0;
let sumD2 = 0, countD2 = 0;
let sumD3 = 0, countD3 = 0;
let sumD4 = 0, countD4 = 0;
let sumD5 = 0, countD5 = 0;
let sumD6 = 0, countD6 = 0;
let sumD7 = 0, countD7 = 0;

validStocks.forEach(i => {
totalProfitRatioSum += i.profitRatio;
if(i.isWin) winCount++;

if (timeMode === 'mode4') {
if (i.d1Profit !== null && i.d1Profit !== undefined) { sumD1 += i.d1Profit; countD1++; }
if (i.d2Profit !== null && i.d2Profit !== undefined) { sumD2 += i.d2Profit; countD2++; }
if (i.d3Profit !== null && i.d3Profit !== undefined) { sumD3 += i.d3Profit; countD3++; }
if (i.d4Profit !== null && i.d4Profit !== undefined) { sumD4 += i.d4Profit; countD4++; }
if (i.d5Profit !== null && i.d5Profit !== undefined) { sumD5 += i.d5Profit; countD5++; }
if (i.d6Profit !== null && i.d6Profit !== undefined) { sumD6 += i.d6Profit; countD6++; }
if (i.d7Profit !== null && i.d7Profit !== undefined) { sumD7 += i.d7Profit; countD7++; }
}
});

const strategyTotalProfitRatio = totalValidCount > 0 ? (totalProfitRatioSum / totalValidCount).toFixed(2) : "0.00";
const winRate = totalValidCount > 0 ? ((winCount / totalValidCount) * 100).toFixed(1) : "0.0";

const profitColorClass = strategyTotalProfitRatio > 0 ? 'text-red-500' : strategyTotalProfitRatio < 0 ? 'text-green-500' : 'text-slate-300';
const profitSign = strategyTotalProfitRatio > 0 ? '+' : '';
const maxDays = totalValidCount > 0 ? Math.max(1, ...validStocks.map(s => s.daysAvailable || 1)) : 1;
const refStock = validStocks[0] || {};
const refD1 = refStock.d1Date || '--';
const refD2 = refStock.d2Date || '--';
const refD3 = refStock.d3Date || '--';
const refD4 = refStock.d4Date || '--';
const refD5 = refStock.d5Date || '--';
const refD6 = refStock.d6Date || '--';
const refD7 = refStock.d7Date || '--';
let mode4HeaderHtml = '';
let theadHtml = '';

if (timeMode === 'mode4') {
const avgD1 = countD1 > 0 ? (sumD1 / countD1).toFixed(2) : "0.00";
const avgD2 = countD2 > 0 ? (sumD2 / countD2).toFixed(2) : "0.00";
const avgD3 = countD3 > 0 ? (sumD3 / countD3).toFixed(2) : "0.00";
const avgD4 = countD4 > 0 ? (sumD4 / countD4).toFixed(2) : "0.00";
const avgD5 = countD5 > 0 ? (sumD5 / countD5).toFixed(2) : "0.00";
const avgD6 = countD6 > 0 ? (sumD6 / countD6).toFixed(2) : "0.00";
const avgD7 = countD7 > 0 ? (sumD7 / countD7).toFixed(2) : "0.00";

mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-6 text-sm items-center flex-wrap justify-end w-full lg:w-auto mt-2 lg:mt-0">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center"><span class="text-slate-400 text-xs uppercase mb-1">有效股票</span><span class="text-white font-mono text-base font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+0</span><span class="font-mono text-sm font-bold my-0.5 \${avgD1 > 0 ? 'text-red-500' : avgD1 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD1 > 0 ? '+' : ''}\${avgD1}%</span><span class="text-blue-300 text-xs">(\${refD1})</span></div>\`;
if (maxDays >= 2) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+1</span><span class="font-mono text-sm font-bold my-0.5 \${avgD2 > 0 ? 'text-red-500' : avgD2 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD2 > 0 ? '+' : ''}\${avgD2}%</span><span class="text-blue-300 text-xs">(\${refD2})</span></div>\`;
if (maxDays >= 3) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+2</span><span class="font-mono text-sm font-bold my-0.5 \${avgD3 > 0 ? 'text-red-500' : avgD3 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD3 > 0 ? '+' : ''}\${avgD3}%</span><span class="text-blue-300 text-xs">(\${refD3})</span></div>\`;
if (maxDays >= 4) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+3</span><span class="font-mono text-sm font-bold my-0.5 \${avgD4 > 0 ? 'text-red-500' : avgD4 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD4 > 0 ? '+' : ''}\${avgD4}%</span><span class="text-blue-300 text-xs">(\${refD4})</span></div>\`;
if (maxDays >= 5) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+4</span><span class="font-mono text-sm font-bold my-0.5 \${avgD5 > 0 ? 'text-red-500' : avgD5 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD5 > 0 ? '+' : ''}\${avgD5}%</span><span class="text-blue-300 text-xs">(\${refD5})</span></div>\`;
if (maxDays >= 6) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+5</span><span class="font-mono text-sm font-bold my-0.5 \${avgD6 > 0 ? 'text-red-500' : avgD6 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD6 > 0 ? '+' : ''}\${avgD6}%</span><span class="text-blue-300 text-xs">(\${refD6})</span></div>\`;
if (maxDays >= 7) mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4 w-16 sm:w-20"><span class="text-slate-300 text-xs font-bold uppercase">T+6</span><span class="font-mono text-sm font-bold my-0.5 \${avgD7 > 0 ? 'text-red-500' : avgD7 < 0 ? 'text-green-500' : 'text-slate-300'}">\${avgD7 > 0 ? '+' : ''}\${avgD7}%</span><span class="text-blue-300 text-xs">(\${refD7})</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-center justify-center border-l border-slate-700 pl-4"><span class="text-purple-400 text-xs uppercase font-bold mb-1">累计总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-lg">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">预警价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+0 (当日)</th>\`;
if (maxDays >= 2) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+1 (次日)</th>\`;
if (maxDays >= 3) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+2 (三日)</th>\`;
if (maxDays >= 4) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+3 (四日)</th>\`;
if (maxDays >= 5) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+4 (五日)</th>\`;
if (maxDays >= 6) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+5 (六日)</th>\`;
if (maxDays >= 7) theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">T+6 (七日)</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right text-purple-300 whitespace-nowrap">累计盈亏</th>\`;
} else {
mode4HeaderHtml += \`<div class="flex gap-4 sm:gap-8 text-sm items-center">\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">有效股票数</span><span class="text-white font-mono font-bold">\${totalValidCount}</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">胜率</span><span class="text-white font-mono font-bold">\${winRate}%</span></div>\`;
mode4HeaderHtml += \`<div class="flex flex-col items-end"><span class="text-slate-500 text-[10px] uppercase">策略总盈亏</span><span class="\${profitColorClass} font-bold font-mono text-base">\${profitSign}\${strategyTotalProfitRatio}%</span></div>\`;
mode4HeaderHtml += \`</div>\`;

theadHtml += \`<th class="p-4 font-medium text-right text-blue-300 whitespace-nowrap">文档买入价</th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">结算收盘价 <span class="text-[9px] text-slate-500 normal-case tracking-normal">(取值日期)</span></th>\`;
theadHtml += \`<th class="p-4 font-medium text-right whitespace-nowrap">单只盈亏比</th>\`;
}
let tbodyHtml = '';
list.forEach(i => {
const pColor = i.profitRatio > 0 ? 'text-red-500' : i.profitRatio < 0 ? 'text-green-500' : 'text-slate-400';
const statusTag = i.error ? '<span class="px-2 py-1 rounded bg-slate-500/30 text-slate-400 border border-slate-500/50 whitespace-nowrap">未收录</span>' :
i.isWin ? '<span class="px-2 py-1 rounded bg-red-500/10 text-red-500 border border-red-500/20 whitespace-nowrap">盈利</span>' :
i.isTie ? '<span class="px-2 py-1 rounded bg-slate-500/10 text-slate-400 border border-slate-500/20 whitespace-nowrap">平盘</span>' :
'<span class="px-2 py-1 rounded bg-green-500/10 text-green-500 border border-green-500/20 whitespace-nowrap">亏损</span>';

let rowInnerHtml = '';
if (timeMode === 'mode4') {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap align-middle">\${i.price.toFixed(2)}</td>\`;

if (i.error) {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 2) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 3) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 4) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 5) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 6) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
if (maxDays >= 7) rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-500">--</td>\`;
} else {
const c1 = i.d1Profit > 0 ? 'text-red-500' : i.d1Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d1Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c1} py-0.5">\${(i.d1Profit>0?'+':'')}\${i.d1Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d1Date})</div>
</td>\`;

if (maxDays >= 2) {
if (i.d2Close) {
const c2 = i.d2Profit > 0 ? 'text-red-500' : i.d2Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d2Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c2} py-0.5">\${(i.d2Profit>0?'+':'')}\${i.d2Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d2Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}

if (maxDays >= 3) {
if (i.d3Close) {
const c3 = i.d3Profit > 0 ? 'text-red-500' : i.d3Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d3Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c3} py-0.5">\${(i.d3Profit>0?'+':'')}\${i.d3Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d3Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
if (maxDays >= 4) {
if (i.d4Close) {
const c4 = i.d4Profit > 0 ? 'text-red-500' : i.d4Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d4Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c4} py-0.5">\${(i.d4Profit>0?'+':'')}\${i.d4Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d4Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
if (maxDays >= 5) {
if (i.d5Close) {
const c5 = i.d5Profit > 0 ? 'text-red-500' : i.d5Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d5Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c5} py-0.5">\${(i.d5Profit>0?'+':'')}\${i.d5Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d5Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
if (maxDays >= 6) {
if (i.d6Close) {
const c6 = i.d6Profit > 0 ? 'text-red-500' : i.d6Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d6Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c6} py-0.5">\${(i.d6Profit>0?'+':'')}\${i.d6Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d6Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
if (maxDays >= 7) {
if (i.d7Close) {
const c7 = i.d7Profit > 0 ? 'text-red-500' : i.d7Profit < 0 ? 'text-green-500' : 'text-slate-300';
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle">
<div class="text-slate-200 text-sm">\${i.d7Close.toFixed(2)}</div>
<div class="font-bold text-xs \${c7} py-0.5">\${(i.d7Profit>0?'+':'')}\${i.d7Profit.toFixed(2)}%</div>
<div class="text-slate-400 text-xs">(\${i.d7Date})</div>
</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono whitespace-nowrap align-middle text-slate-600">--</td>\`;
}
}
}
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} text-sm whitespace-nowrap align-middle">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
} else {
rowInnerHtml += \`<td class="p-4 text-right font-mono text-blue-300 font-bold whitespace-nowrap">\${i.price.toFixed(2)}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono text-slate-300 whitespace-nowrap">\${i.error ? '--' : \`\${i.closePrice.toFixed(2)} <br><span class="text-[10px] text-slate-500 font-bold">(\${i.matchedDate})</span>\`}</td>\`;
rowInnerHtml += \`<td class="p-4 text-right font-mono font-bold \${pColor} whitespace-nowrap">\${i.error ? '--' : (i.profitRatio > 0 ? '+' : '') + i.profitRatio.toFixed(2) + '%'}</td>\`;
}
tbodyHtml += \`
<tr class="hover:bg-slate-800/60 transition-colors \${i.error ? 'opacity-40' : ''}">
<td class="p-4 align-middle">
<div class="text-blue-400 font-bold whitespace-nowrap">\${i.code}</div>
<div class="text-slate-300 whitespace-nowrap flex items-center gap-1">
\${i.name}
<span class="text-[10px] text-slate-600 opacity-50 font-normal cursor-default select-none">\${i.provider || ''}</span>
</div>
</td>
<td class="p-4 text-slate-400 font-mono whitespace-nowrap align-middle">\${i.date} \${i.time}</td>
\${rowInnerHtml}
<td class="p-4 text-center text-[10px] font-bold align-middle">\${statusTag}</td>
</tr>
\`;
});
const groupHtml = \`
<div class="card overflow-hidden shadow-xl animate-row border border-slate-700 w-full">
<div class="group-header bg-slate-800 p-4 border-b border-slate-700 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4" onclick="toggleAccordion('body-\${groupId}')">
<div class="flex items-center gap-3">
<i class="fa-solid fa-chevron-down chevron-icon text-slate-400"></i>
<span class="bg-indigo-600/30 text-indigo-300 text-xs px-2 py-1 rounded border border-indigo-500/30 font-bold truncate max-w-[200px]" title="\${strategyName}">
\${strategyName}
</span>
\${totalValidCount < list.length ? \`<span class="text-[10px] bg-red-900/40 text-red-400 px-2 py-0.5 rounded border border-red-800/50">屏蔽 \${list.length - totalValidCount} 支无数据</span>\` : ''}
</div>
\${mode4HeaderHtml}
</div>

<div id="body-\${groupId}" class="strategy-body hidden overflow-x-auto bg-[#172033]">
<table class="w-full text-xs text-left">
<thead class="text-slate-400 bg-slate-900/50 uppercase">
<tr>
<th class="p-4 font-medium whitespace-nowrap">股票信息</th>
<th class="p-4 font-medium whitespace-nowrap">预警时间</th>
\${theadHtml}
<th class="p-4 font-medium text-center whitespace-nowrap">状态</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-800/50">
\${tbodyHtml}
</tbody>
</table>
</div>
</div>
\`;
container.insertAdjacentHTML('beforeend', groupHtml);

list.strategyTotalProfitRatio = strategyTotalProfitRatio;
list.validCount = totalValidCount;
}
document.getElementById('screenshotBtn').addEventListener('click', async function() {
const btn = this;
const originalHTML = btn.innerHTML;
const resultsDiv = document.getElementById('results');

btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> 生成图中...';
btn.disabled = true;
try {
const canvas = await html2canvas(resultsDiv, {
backgroundColor: '#0f172a',
scale: 3,
useCORS: true,
logging: false,
allowTaint: true
});

const imgData = canvas.toDataURL('image/png', 1.0);
const link = document.createElement('a');
link.href = imgData;
link.download = getDynamicFileName('png');
link.click();
} catch (err) {
alert("生成图片失败: " + err.message);
} finally {
btn.innerHTML = originalHTML;
btn.disabled = false;
}
});
document.getElementById('exportBtn').onclick = () => {
let csv = "";

finalData.forEach(group => {
const timeMode = group.timeMode;
const maxD = timeMode === 'mode4' ? Math.max(1, ...group.items.filter(i=>!i.error).map(s=>s.daysAvailable||1)) : 1;

if (timeMode === 'mode4') {
csv += "\\ufeff预警时间,股票代码,股票名称,文档预警价,T+0取值日期,T+0收盘价,T+0单日盈亏";
if (maxD >= 2) csv += ",T+1取值日期,T+1收盘价,T+1单日盈亏";
if (maxD >= 3) csv += ",T+2取值日期,T+2收盘价,T+2单日盈亏";
if (maxD >= 4) csv += ",T+3取值日期,T+3收盘价,T+3单日盈亏";
if (maxD >= 5) csv += ",T+4取值日期,T+4收盘价,T+4单日盈亏";
if (maxD >= 6) csv += ",T+5取值日期,T+5收盘价,T+5单日盈亏";
if (maxD >= 7) csv += ",T+6取值日期,T+6收盘价,T+6单日盈亏";
csv += ",累计总盈亏,状态,策略名称\\n";
} else {
csv += "\\ufeff预警时间,股票代码,股票名称,文档买入基准,结算收盘价,取价日期,单只盈亏比,状态,策略名称\\n";
}
group.items.forEach(s => {
const status = s.error ? "未收录" : (s.isWin ? "盈利" : s.isTie ? "平盘" : "亏损");

if (timeMode === 'mode4') {
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\`;
csv += \`"\${s.error ? '--' : s.d1Date}",\${s.error ? 0 : s.d1Close.toFixed(2)},\${s.error ? 0 : s.d1Profit.toFixed(2)}%,\`;
if (maxD >= 2) csv += \`"\${s.d2Date||'--'}",\${s.d2Close ? s.d2Close.toFixed(2) : '--'},\${s.d2Profit !== null ? s.d2Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 3) csv += \`"\${s.d3Date||'--'}",\${s.d3Close ? s.d3Close.toFixed(2) : '--'},\${s.d3Profit !== null ? s.d3Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 4) csv += \`"\${s.d4Date||'--'}",\${s.d4Close ? s.d4Close.toFixed(2) : '--'},\${s.d4Profit !== null ? s.d4Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 5) csv += \`"\${s.d5Date||'--'}",\${s.d5Close ? s.d5Close.toFixed(2) : '--'},\${s.d5Profit !== null ? s.d5Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 6) csv += \`"\${s.d6Date||'--'}",\${s.d6Close ? s.d6Close.toFixed(2) : '--'},\${s.d6Profit !== null ? s.d6Profit.toFixed(2) + '%' : '--'},\`;
if (maxD >= 7) csv += \`"\${s.d7Date||'--'}",\${s.d7Close ? s.d7Close.toFixed(2) : '--'},\${s.d7Profit !== null ? s.d7Profit.toFixed(2) + '%' : '--'},\`;
csv += \`\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
} else {
const mDate = s.error ? "--" : s.matchedDate;
csv += \`"\${s.date} \${s.time}","\${s.code}","\${s.name}",\${s.price.toFixed(2)},\${s.error ? 0 : s.closePrice.toFixed(2)},"\${mDate}",\${s.error ? 0 : s.profitRatio.toFixed(2)}%,"\${status}","\${group.strategy}"\\n\`;
}
});

csv += \`"统计信息","有效股票数量:\${group.items.validCount}",,,,,"策略总盈亏:",\${group.items.strategyTotalProfitRatio}%,,"\${group.strategy} 汇总"\\n\\n\`;
});
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = getDynamicFileName('csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};

// 新增:打赏弹窗逻辑 - 独立作用域,不影响原有代码
(function() {
// 收款码配置
const ALIPAY_IMG_URL = "https://pan.l42.cn/d/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E5%BA%8A/%E6%94%AF%E4%BB%98%E5%AE%9D%E6%94%B6%E6%AC%BE%E7%A0%81.png?sign=gwjNVxW0-zJce_mn_RKvZGVqv8WkartY1AJVE2FWc2c=:0";
const WECHAT_IMG_URL = "https://pan.l42.cn/d/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E5%BA%8A/%E5%BE%AE%E4%BF%A1%E6%94%B6%E6%AC%BE%E7%A0%81.png?sign=BkrSxjigUugAEQhE0bFfKFnODyqtzC9GDNL1S3i5Xgs=:0";

// 元素获取
const modal = document.getElementById('rewardModal');
const modalOverlay = document.getElementById('modalOverlay');
const modalContent = document.getElementById('modalContent');
const modalTitle = document.getElementById('modalTitle');
const modalImg = document.getElementById('modalImg');
const alipayBtn = document.getElementById('alipayBtn');
const wechatBtn = document.getElementById('wechatBtn');

// 打开弹窗
function openModal(title, imgSrc) {
modalTitle.innerText = title;
modalImg.src = imgSrc;
modal.classList.remove('hidden');
document.body.style.overflow = 'hidden'; // 禁止背景滚动
}

// 关闭弹窗
function closeModal() {
modal.classList.add('hidden');
document.body.style.overflow = ''; // 恢复背景滚动
modalImg.src = ''; // 清空src,优化加载
}

// 按钮点击事件
alipayBtn.addEventListener('click', () => {
openModal('支付宝打赏', ALIPAY_IMG_URL);
});

wechatBtn.addEventListener('click', () => {
openModal('微信打赏', WECHAT_IMG_URL);
});

// 点击遮罩空白区域关闭
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) closeModal();
});

// 点击弹窗内容区域不关闭
modalContent.addEventListener('click', (e) => e.stopPropagation());

// ESC键关闭弹窗
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
closeModal();
}
});
})();
</script>
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html;charset=UTF-8" } });
}
};