fetch data bug fix for both index and DVA/DCA calculation

This commit is contained in:
2026-02-02 06:48:49 +08:00
parent d33b521b22
commit 6506932042
15 changed files with 35346 additions and 16918 deletions
+82 -105
View File
@@ -138,7 +138,7 @@
<thead>
<tr>
<th style="width: 25%;">Instrument</th>
<th style="width: 10%;">Close</th>
<th style="width: 10%;">Date</th> <th style="width: 10%;">Close</th>
<th style="width: 10%;">Chg%</th>
<th style="width: 10%;">52W Range</th> <th style="width: 8%;">20 EMA</th>
<th style="width: 10%;">50 EMA</th>
@@ -159,117 +159,115 @@
console.log("Script block loaded successfully.");
// --- 1. Helper Function for K/D Styling ---
// Defined at the top level so it's ready before loadData runs
function formatKD(val) {
if (!val || val === "N/A" || !val.includes('/')) return `<span class="text-muted">N/A</span>`;
const [k, d] = val.split('/').map(v => parseFloat(v));
let colorClass = 'text-dark'; // Default
if (k >= 80) colorClass = 'text-danger fw-bold'; // Overbought
else if (k <= 20) colorClass = 'text-success fw-bold'; // Oversold
let colorClass = 'text-dark';
if (k >= 80) colorClass = 'text-danger fw-bold';
else if (k <= 20) colorClass = 'text-success fw-bold';
return `<span class="${colorClass}">${val}</span>`;
}
// --- 2. Load Table Data (Fast) ---
// --- 2. EMA Formatter ---
const formatEma = (val) => {
if (val === "N/A" || val === null || val === undefined) return `<span class="text-muted">N/A</span>`;
const num = parseFloat(val);
const sign = num > 0 ? "+" : "";
const colorClass = num >= 0 ? 'text-up' : 'text-down';
return `<span class="${colorClass}">${sign}${num.toFixed(1)}%</span>`;
};
// --- 3. Load Table Data ---
async function loadData() {
console.log("Starting loadData...");
const loading = document.getElementById('loading');
const tbody = document.getElementById('tableBody');
if (loading) loading.style.display = 'inline';
try {
const response = await fetch('/api/summary');
const data = await response.json();
tbody.innerHTML = '';
if (!data || data.length === 0) {
tbody.innerHTML = '<tr><td colspan="9" class="p-4">No data found. Please run Sync.</td></tr>';
tbody.innerHTML = '<tr><td colspan="10" class="p-4">No data found. Please run Sync.</td></tr>';
return;
}
data.forEach(item => {
// 1. GATEKEEPER: Check if the item has an error or is missing data
if (item.error || !item.last_close) {
const errorRow = `
// Get today's date string (YYYY-MM-DD) to check freshness
const todayStr = new Date().toISOString().split('T')[0];
let htmlContent = '';
data.forEach(item => {
// --- 1. Error Row Handling ---
if (item.error || !item.last_close) {
htmlContent += `
<tr>
<td>${item.symbol || 'Unknown'}</td>
<td colspan="9" class="text-center p-3">
<span class="badge bg-warning text-dark"><i class="bi bi-exclamation-triangle"></i> Needs Sync</span>
<small class="text-muted ms-2">Local CSV not found or corrupted.</small>
</td>
</tr>`;
return;
}
let displayDate = "N/A";
if (item.last_date && item.last_date.includes('-')) {
const parts = item.last_date.split('-'); // Splits "2026-01-30" into ["2026", "01", "30"]
displayDate = `${parts[2]}/${parts[1]}`; // Combines into "30/01"
}
// --- 2. Calculations & Styling ---
const current = parseFloat(item.last_close) || 0;
const low = parseFloat(item.low_52) || 0;
const high = parseFloat(item.high_52) || 0;
// 52W Range Progress Bar
let rangePct = high > low ? Math.min(Math.max(((current - low) / (high - low)) * 100, 0), 100) : 0;
const rangeColor = rangePct > 80 ? 'text-danger' : (rangePct < 20 ? 'text-success' : 'text-muted');
// Date Freshness check (highlight if date matches today)
const isFresh = item.last_date === todayStr;
const dateStyle = isFresh ? 'badge bg-success-subtle text-success border border-success-subtle' : 'text-muted';
// --- 3. Construct Row ---
htmlContent += `
<tr>
<td>${item.symbol || 'Unknown'}</td>
<td colspan="8" class="text-center p-3">
<span class="badge bg-warning text-dark">
<i class="bi bi-exclamation-triangle"></i> Needs Sync
</span>
<small class="text-muted ms-2">Local CSV not found or corrupted.</small>
<td>${item.symbol}</td>
<td><span class="${dateStyle}" style="font-size: 0.75rem; padding: 2px 5px; border-radius: 4px;">${displayDate}</span></td>
<td class="fw-bold">${item.last_close}</td>
<td class="${item.change_pct >= 0 ? 'text-up' : 'text-down'}">
${item.change_pct >= 0 ? '+' : ''}${item.change_pct}%
</td>
</tr>
`;
tbody.innerHTML += errorRow;
return; // This skips the rest of the math and goes to the next fund
}
<td class="${rangeColor} small">
<div class="d-flex justify-content-between mb-1" style="min-width: 100px; font-size: 0.7rem;">
<span>${item.low_52}</span><span>${item.high_52}</span>
</div>
<div class="progress" style="height: 4px;">
<div class="progress-bar bg-primary" style="width: ${rangePct}%"></div>
</div>
</td>
<td>${formatEma(item.last_ema20)}</td>
<td>${formatEma(item.last_ema50)}</td>
<td>${formatEma(item.last_ema100)}</td>
<td>${formatEma(item.last_ema200)}</td>
<td>${formatKD(item.kd_values)}</td>
</tr>`;
});
// --- A. Helper for EMA colors (Your existing code) ---
const formatEma = (val) => {
if (val === "N/A" || val === null || val === undefined) return `<span class="text-muted">N/A</span>`;
const num = parseFloat(val);
const sign = num > 0 ? "+" : "";
const colorClass = num >= 0 ? 'text-up' : 'text-down';
return `<span class="${colorClass}">${sign}${num.toFixed(1)}%</span>`;
};
// Batch update the DOM once
tbody.innerHTML = htmlContent;
// --- B. Calculate 52W Range logic ---
const current = parseFloat(item.last_close) || 0;
const low = parseFloat(item.low_52) || 0;
const high = parseFloat(item.high_52) || 0;
let rangePct = 0;
if (high > low) {
rangePct = ((current - low) / (high - low)) * 100;
rangePct = Math.min(Math.max(rangePct, 0), 100);
}
const rangeColor = rangePct > 80 ? 'text-danger' : (rangePct < 20 ? 'text-success' : 'text-muted');
// --- C. Build the Row (Your existing code) ---
const row = `
<tr>
<td>${item.symbol}</td>
<td class="fw-bold">${item.last_close}</td>
<td class="${item.change_pct >= 0 ? 'text-up' : 'text-down'}">
${item.change_pct >= 0 ? '+' : ''}${item.change_pct}%
</td>
<td class="${rangeColor} small">
<div class="d-flex justify-content-between mb-1" style="min-width: 100px;">
<span>${item.low_52}</span>
<span>${item.high_52}</span>
</div>
<div class="progress" style="height: 5px;">
<div class="progress-bar bg-primary" style="width: ${rangePct}%"></div>
</div>
</td>
<td>${formatEma(item.last_ema20)}</td>
<td>${formatEma(item.last_ema50)}</td>
<td>${formatEma(item.last_ema100)}</td>
<td>${formatEma(item.last_ema200)}</td>
<td>${formatKD(item.kd_values)}</td>
</tr>
`;
tbody.innerHTML += row;
});
} catch (error) {
console.error("Fetch error:", error);
tbody.innerHTML = '<tr><td colspan="9" class="text-danger p-4">Error loading local data. Check Console.</td></tr>';
tbody.innerHTML = '<tr><td colspan="10" class="text-danger p-4">Error loading summary. Check server logs.</td></tr>';
} finally {
if (loading) loading.style.display = 'none';
}
}
// --- 3. Run Global Sync (Slow) ---
// --- 4. Global Sync ---
async function runGlobalSync() {
const syncBtn = document.getElementById('syncBtn');
const loading = document.getElementById('loading');
if (!syncBtn) return;
syncBtn.disabled = true;
@@ -279,13 +277,12 @@
try {
const response = await fetch('/api/sync', { method: 'POST' });
if (!response.ok) throw new Error("Server error during sync");
await loadData(); // Reload table after sync
alert("Sync Complete! Data updated.");
if (!response.ok) throw new Error("Sync failed");
await loadData();
alert("Sync Complete!");
} catch (error) {
console.error("Sync error:", error);
alert("Sync failed. Check terminal for Python errors.");
alert("Sync failed. Check terminal.");
} finally {
syncBtn.disabled = false;
syncBtn.innerHTML = originalText;
@@ -293,28 +290,8 @@
}
}
// --- 4. Initial Trigger ---
window.onload = function() {
loadData();
};
scales: {
y: {
ticks: {
callback: function(value) {
return '$' + value.toLocaleString();
}
}
}
}
const vaROI = ((last.va_value - last.va_invested) / last.va_invested * 100).toFixed(2);
const dcaROI = ((last.dca_value - last.dca_invested) / last.dca_invested * 100).toFixed(2);
summaryText.innerHTML = `
<div class="row text-center">
<div class="col"><strong>VA ROI:</strong> ${vaROI}%</div>
<div class="col"><strong>DCA ROI:</strong> ${dcaROI}%</div>
</div>
`;
// --- 5. Initial Load ---
window.addEventListener('load', loadData);
</script>
</body>