-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdiscount.html
More file actions
621 lines (564 loc) · 24.9 KB
/
Copy pathdiscount.html
File metadata and controls
621 lines (564 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Phân Tích Cổ Phiếu</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3.0.1/dist/chartjs-plugin-annotation.min.js"></script>
<style>
body {
overflow:hidden;
font-family: Inter, Nunito Sans, Lexend, Noto Sans, Arial, sans-serif;
font-size: 14px;
background-color: #fff;
margin: auto;
padding: 10px;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background-color: #f4f4f9;
padding: 10px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
width: 100%;
max-width: 400px;
line-height: 24px;
}
h1 {
font-size: 16px;
margin: 5px;
text-align: center;
}
label {
display: block;
margin-top: 5px;
font-weight: bold;
}
input {
padding: 10px;
margin-top: 5px;
margin-bottom: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group {
display: flex;
align-items: center;
}
.input-group span {
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ccc;
border-left: none;
border-radius: 0 4px 4px 0;
}
button {
font-family: Inter, Nunito Sans, Lexend, Noto Sans, Arial, sans-serif;
font-size: 14px;
background-color: #007bff;
color: white;
padding: 8px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.result {
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ccc;
border-radius: 4px;
}
input#stockCode {
text-transform: uppercase;
/* Chuyển tự động thành chữ in hoa */
}
</style>
<style>
table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
th,
td {
padding: 8px;
text-align: left;
}
::-webkit-scrollbar-track {
box-shadow: inset 0 0 0 grey;
border-radius: 1px;
}
::-webkit-scrollbar-thumb {
background: #ccc;
border-radius: 10px
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
background: transparent;
}
.tabGroup {
display: flex;
margin-bottom: 10px;
}
.tab-g {
padding: 6px 6px;
cursor: pointer;
border: 1px solid #ccc;
border-bottom: none;
}
.tab-g.active {
background-color: #007bff;
color: white;
}
tbody tr:not(:last-child) {
border-bottom: 1px solid #ccc;
}
thead {
border-bottom: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="stockCode" value="VN-INDEX" placeholder="Nhập mã cổ phiếu...">
<button onclick="analyzeStock()">Thống kê</button>
<div class="tabGroup">
<div class="tab-g active" onclick="selectTab('resultBox')">Kết quả</div>
<div class="tab-g" onclick="selectTab('scratter')">Biểu đồ phân tán</div>
<div class="tab-g" onclick="selectTab('table')">Bảng dữ liệu</div>
</div>
<div class="result" style="height:230px;" id="resultBox">Kết quả sẽ hiển thị tại đây...</div>
<canvas id="stockChart" style="display:none;height:200px;"></canvas>
<table id="resultsTable" style="display:none;height:230px; overflow:auto;">
<thead style="position">
<tr>
<th>Tạo đỉnh</th>
<th>Giá</th>
<th>Tạo đáy</th>
<th>Giá</th>
<th>Chiết khấu (%)</th>
<th>Hồi phục (%)</th>
</tr>
</thead>
<tbody>
<!-- Data will be populated here -->
</tbody>
</table>
</div>
<script>
const ams = new URLSearchParams(window.location.search);
let ckht = ``, stockCode =ams.get("code")||'VN-INDEX';
document.getElementById("stockCode").value = stockCode;
fetchData(stockCode);
// phân tích
function analyzeStock() {
// Lấy giá trị từ các ô nhập liệu
stockCode = document.getElementById("stockCode").value.trim().toUpperCase();
// Kiểm tra đầu vào
if (!stockCode || stockCode.length < 3) {
document.getElementById("resultBox").innerText = "Vui lòng nhập mã cổ phiếu hợp lệ.";
return;
}
// Xử lý dữ liệu
fetchData(stockCode);
selectTab('resultBox')
}
function selectTab(tabName) {
const tabs = document.querySelectorAll('.tab-g');
tabs.forEach(tab => {
tab.classList.remove('active');
});
document.querySelector(`.tab-g[onclick="selectTab('${tabName}')"]`).classList.add('active');
if (tabName == 'table') {
document.getElementById("resultsTable").style.display = 'block';
document.getElementById("stockChart").style.display = 'none';
document.getElementById("resultBox").style.display = 'none';
}
if (tabName == 'scratter') {
document.getElementById("stockChart").style.display = 'block';
document.getElementById("resultsTable").style.display = 'none';
document.getElementById("resultBox").style.display = 'none';
}
if (tabName == 'resultBox') {
document.getElementById("resultBox").style.display = 'block';
document.getElementById("resultsTable").style.display = 'none';
document.getElementById("stockChart").style.display = 'none';
}
}
function formatTimestamp(timestamp) {
// Chuyển đổi timestamp (giây) sang milliseconds
const date = new Date(timestamp * 1000);
// Lấy ngày, tháng và năm
const day = String(date.getDate()).padStart(2, '0'); // Đảm bảo 2 chữ số
const month = String(date.getMonth() + 1).padStart(2, '0'); // Tháng bắt đầu từ 0
const year = String(date.getFullYear()).slice(-2); // Lấy 2 chữ số cuối của năm
// Trả về định dạng dd/mm/yy
return `${day}/${month}/${year}`;
}
function getCurrentDate() {
const t = new Date;
return t.getFullYear() + "-" + String(t.getMonth() + 1)
.padStart(2, "0") + "-" + String(t.getDate())
.padStart(2, "0")
}
async function fetchData(code) {
const apiUrl = "https://mastrade.masvn.com/api/v1/tradingview/history?symbol=" + code + "&resolution=1D&from=1420070400&to=" + parseInt(Date.parse(getCurrentDate()) / 1000);
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
var ohlc = [],
closep = [];
for (var i = 0; i < data.t.length; i += 1) {
let k = 1000;
ohlc.push({
"time": parseInt(data.t[i]),
"open": parseFloat(data.o[i]),
"high": parseFloat(data.h[i]),
"low": parseFloat(data.l[i]),
"close": parseFloat(data.c[i])
});
closep.push({
"time": data.t[i],
"value": parseFloat(data.c[i])
});
}
var drawdown = findRecoveries(closep);
var sampleData = [],
sampleData2 = [];
for (let i = 1; i < drawdown.length; i++) {
sampleData.push(drawdown[i].drawdown)
sampleData2.push(drawdown[i].recover)
}
const ci = calculateConfidenceInterval(sampleData);
const ci2 = calculateConfidenceInterval(sampleData2);
renderResults(drawdown.slice(-20))
const mockResult = `Kết quả thống kê cho mã: <b title="Số lần tạo đáy và hồi phục thành công">${code} (${drawdown.length})</b><br/>Mức chiết khấu trung bình là ${ci.mean.toFixed(2)}% [${ci.lowerBound.toFixed(2)}, ${ci.upperBound.toFixed(2)}].<br/>Mức hồi phục trung bình là ${ci2.mean.toFixed(2)}% [${ci2.lowerBound.toFixed(2)}, ${ci2.upperBound.toFixed(2)}]<br/> ${ckht}`;
// Hiển thị kết quả
document.getElementById("resultBox").innerHTML = mockResult;
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
document.getElementById("resultBox").innerHTML = `Mã cổ phiếu không hợp lệ, hoặc lỗi không lấy được dữ liệu<br/> ${error}`;
}
}
function calculateConfidenceInterval(data) {
if (data.length === 0) return null; // Kiểm tra nếu mảng trống
const n = data.length;
const mean = data.reduce((sum, value) => sum + value, 0) / n;
// Tính độ lệch chuẩn
const variance = data.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / (n - 1);
const standardDeviation = Math.sqrt(variance);
// Sai số chuẩn
const standardError = standardDeviation / Math.sqrt(n);
// Giá trị Z cho mức tin cậy 95%
const zScore = 1.96;
// Khoảng tin cậy
const marginOfError = zScore * standardError;
const lowerBound = mean - marginOfError;
const upperBound = mean + marginOfError;
return {
mean,
lowerBound,
upperBound,
standardDeviation,
marginOfError,
n
};
}
function calculateMA(data, period) {
return data.map((_, index) => {
if (index < period - 1) return null;
const slice = data.slice(index - period + 1, index + 1);
const average = slice.reduce((sum, val) => sum + val, 0) / period;
return average;
});
}
function findRecoveries(data) {
const results = [];
var ab = data.map(s => s.value);
var ma10 = calculateMA(ab, 20); // tính MA10
let peak = data[0].value; // Giá đỉnh ban đầu
let tpeak = data[0].time; // Giá đỉnh ban đầu
let trough = data[0].value; // Giá đáy ban đầu
let ttrough = data[0].time; // Giá đáy ban đầu
let inDecline = false; // Trạng thái đang sụt giảm, mặc định là không
for (let i = 1; i < data.length; i++) {
if (!inDecline) { // đang tăng
if (data[i].value < peak) { // Bắt đầu sụt giảm
inDecline = true;
trough = data[i].value;
ttrough = data[i].time;
} else {
peak = data[i].value; // Cập nhật đỉnh nếu vẫn tăng
tpeak = data[i].time;
inDecline = false;
}
} else { // đang giảm
if (trough > data[i].value) {
trough = data[i].value; // Cập nhật đáy nếu vẫn giảm
ttrough = data[i].time
inDecline = true;
} else {
if (data[i].value > peak) {
peak = data[i].value; // Cập nhật đỉnh nếu giá hồi vượt đỉnh (không có đợt giảm sâu)
tpeak = data[i].time;
inDecline = false;
} else {
// điều kiện xác nhận hồi phục khi đáy ở dưới ma20 và giá hồi phục vượt được ma20
if (data[i].value > ma10[i] && trough < ma10[i]) { // giá vượt ngưỡng phục hồi hoặc vượt MA20
const recoveryDate = data[i].time; // Thời điểm hồi phục
results.push({
drawdown: (1 - trough / peak) * 100,
start: peak,
startDate: formatTimestamp(tpeak),
bottom: trough,
bottomDate: formatTimestamp(ttrough),
recoveryDate: formatTimestamp(recoveryDate),
recoveryPrice: data[i].value,
recover: 0,
});
inDecline = false; // Xác nhận hồi phục
peak = data[i].value; // Reset đỉnh
tpeak = data[i].time; // Reset đỉnh
} else {
// chưa xác nhận đã hồi phục, tiếp tục giảm
inDecline = true;
}
}
}
}
}
// lọc các đợt drawdown <2% do sideway nằm trong biên độ nhỏ
const output = results.filter(item => item.drawdown > 2);
// tính mức hồi phục bằng đỉnh mới- đáy cũ
for (i = 0; i < output.length - 1; i++) {
output[i].recover = 100 * output[i + 1].start / output[i].bottom - 100;
}
output[output.length - 1].recover = 100 * peak / output[output.length - 1].bottom - 100; // tính mức recover
ckht = ''; //reset ckht;
let temp ='';
if (data[data.length - 1].value > trough) {
temp= `<br/>Đã tăng từ đáy ${formatTimestamp(ttrough)}: ${((data[data.length-1].value/trough-1)*100).toFixed(2)}% `;
}else {
temp= `<br/> Đã tăng từ đáy ${results[results.length-1].bottomDate}: ${results[results.length-1].recover.toFixed(2)}%.`;
}
//console.log(results)
if (data[data.length - 1].value * 1.02 < peak) {
let gg = ((1 - data[data.length - 1].value / peak) * 100).toFixed(2);
ckht += `Chiết khấu hiện tại từ đỉnh ${formatTimestamp(tpeak)}: ${gg}%.${temp}<br/>${predict(output, gg)}`;
} else {
let gg = output[output.length - 1].drawdown.toFixed(2);
temp= `<br/> Đã tăng từ đáy ${results[results.length-1].bottomDate}: ${results[results.length-1].recover.toFixed(2)}%.`;
ckht += `Chiết khấu từ đỉnh cũ ${output[output.length-1].startDate}: ${gg}%.${temp}<br/>${predict(output, gg)}`;
}
return output;
}
// vẽ bảng
function renderResults(results) {
const tableBody = document.querySelector('#resultsTable tbody');
tableBody.innerHTML = ''; // Clear existing table data
results.reverse();
// Loop through results array and add rows to the table
results.forEach(result => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${result.startDate}</td>
<td>${result.start.toFixed(0)}</td>
<td>${result.bottomDate}</td>
<td>${result.bottom.toFixed(0)}</td>
<td>${result.drawdown.toFixed(2)}</td>
<td>${result.recover.toFixed(2)}</td>
`;
tableBody.appendChild(row);
});
}
let chartInstance;
//Dự báo
function predict(data, dropValue) {
// Tính toán hồi quy tuyến tính
function calculateRegression(data) {
const n = data.length;
// Tính trung bình của x (drop) và y (recovery)
const meanX = data.reduce((sum, point) => sum + point.drawdown, 0) / n;
const meanY = data.reduce((sum, point) => sum + point.recover, 0) / n;
// Tính Covariance và Variance
let covariance = 0;
let varianceX = 0;
data.forEach(point => {
covariance += (point.drawdown - meanX) * (point.recover - meanY);
varianceX += Math.pow(point.drawdown - meanX, 2);
});
// Tính slope (a) và intercept (b)
const slope = covariance / varianceX;
const intercept = meanY - slope * meanX;
return {
slope,
intercept
};
}
// Dự báo mức hồi phục
function predictRecovery(drop, model) {
const {
slope,
intercept
} = model;
return slope * drop + intercept;
}
// Xây dựng mô hình hồi quy
const model = calculateRegression(data);
// Chuẩn bị dữ liệu cho biểu đồ
const scatterData = data.map(point => ({
x: point.drawdown,
y: point.recover
}));
const regressionLine = [];
for (let x = Math.min(...data.map(d => d.drawdown)) - 0; x <= Math.max(...data.map(d => d.drawdown)) + 5; x += 1) {
regressionLine.push({
x: x,
y: predictRecovery(x, model)
});
}
function findRecoveryLevel(recoveryArray) {
recoveryArray = recoveryArray.filter(obj => obj.drawdown >= dropValue);
recoveryArray.sort((a, b) => a.recover - b.recover);
const index = Math.ceil(recoveryArray.length * 0.1);
//console.log(recoveryArray, index)
return recoveryArray[index];
}
let probabilitys = findRecoveryLevel(data).recover
if (chartInstance) {
chartInstance.destroy();
}
// Vẽ biểu đồ với Chart.js
const ctx = document.getElementById('stockChart').getContext('2d');
chartInstance = new Chart(ctx, {
type: 'scatter',
height: '180',
data: {
datasets: [{
label: 'GT thực',
data: scatterData,
backgroundColor: 'blue',
},
{
label: 'Hồi quy',
data: regressionLine,
type: 'line',
borderColor: 'red',
fill: false,
pointRadius: 0,
},
],
},
options: {
responsive: true,
plugins: {
legend: {
display: false,
position: 'top',
},
title: {
display: false,
text: stockCode + ' Recovery vs Drop (Regression Analysis)',
},
annotation: {
annotations: {
line1: {
type: 'line',
yMin: probabilitys,
yMax: probabilitys,
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2,
label: {
enabled: true,
content: 'Target Line',
position: 'start', // Vị trí nhãn (start, end, center)
backgroundColor: 'rgba(255, 99, 132, 0.2)',
font: {
size: 12,
weight: 'bold',
},
}
},
line2: {
type: 'line',
xMin: dropValue,
xMax: dropValue,
borderColor: 'gray',
borderWidth: 2
}
}
}
},
scales: {
x: {
type: 'linear',
position: 'bottom',
title: {
display: true,
text: stockCode + '- Chiết khấu (%)',
},
},
y: {
title: {
display: true,
text: 'Hồi phục (%)',
},
},
},
},
});
// tương quan
const dropLevels = data.map(d => d.drawdown);
const recoveryLevels = data.map(d => d.recover);
const correlation = calculateCorrelation(dropLevels, recoveryLevels);
const regression = linearRegression(dropLevels, recoveryLevels);
const tValue = tTestCorrelation(correlation, dropLevels.length);
const df = dropLevels.length - 2;
const significant = isSignificant(tValue, df);
return `<i>Mức hồi phục dự báo là: ${probabilitys.toFixed(2)}% (xs 90%)</i><br/>------<br/>Hệ số tương quan: ${correlation.toFixed(2)}<br/>Hệ số hồi quy: Slope = ${regression.slope.toFixed(2)}, Intercept = ${regression.intercept.toFixed(2)}<br>Giá trị t: ${tValue.toFixed(2)}, Mối tương quan ${significant} ý nghĩa thống kê.<br/>`;
}
function calculateCorrelation(x, y) {
const n = x.length;
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0);
const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 0);
const numerator = (n * sumXY) - (sumX * sumY);
const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
return numerator / denominator;
}
function linearRegression(x, y) {
const n = x.length;
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0);
const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
return {
slope,
intercept
};
}
function tTestCorrelation(r, n) {
const t = r * Math.sqrt((n - 2) / (1 - r * r));
return t;
}
function isSignificant(tValue, df, alpha = 0.05) {
const criticalValue = 2.306;
return Math.abs(tValue) > criticalValue ? 'có' : 'không';
}
</script>
</body>
</html>