fetch data bug fix for both index and DVA/DCA calculation
This commit is contained in:
+82
-105
@@ -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>
|
||||
|
||||
+104
-72
@@ -98,7 +98,7 @@
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="card p-3 text-center border-primary h-100">
|
||||
<h6 class="text-muted text-uppercase small">Next Recommended Move</h6>
|
||||
<h6 class="text-muted text-uppercase small">Next Payment Estimates</h6>
|
||||
<h2 id="nextInvAmt" class="fw-bold mb-1">$0.00</h2>
|
||||
<div class="small text-muted mb-2">
|
||||
Price: <span id="latestPriceDisplay" class="fw-bold text-dark">$0.00</span>
|
||||
@@ -188,53 +188,53 @@
|
||||
const originalText = el.btn.innerHTML;
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
symbol: el.symbol.value.trim().toUpperCase(),
|
||||
initial_inv: parseFloat(el.initial.value) || 0,
|
||||
monthly_target: parseFloat(el.monthly.value) || 0,
|
||||
startDate: el.date.value, // Match backend's preferred key
|
||||
frequency: el.freq.value, // <--- CRITICAL: MUST BE SENT
|
||||
allow_sell: el.sell.checked,
|
||||
allow_fractional: el.frac.checked
|
||||
};
|
||||
const payload = {
|
||||
symbol: el.symbol.value.trim().toUpperCase(),
|
||||
initial_inv: parseFloat(el.initial.value) || 0,
|
||||
monthly_target: parseFloat(el.monthly.value) || 0,
|
||||
startDate: el.date.value,
|
||||
frequency: el.freq.value,
|
||||
allow_sell: el.sell.checked,
|
||||
allow_fractional: el.frac.checked
|
||||
};
|
||||
|
||||
if (!payload.symbol) {
|
||||
alert("Please enter a ticker symbol.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Loading State
|
||||
el.btn.disabled = true;
|
||||
el.btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';
|
||||
|
||||
const res = await fetch('/api/backtest', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
// Parse response to check for specific Python errors
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `Server returned ${res.status}`);
|
||||
}
|
||||
|
||||
// Update UI
|
||||
document.getElementById('kpiArea')?.classList.remove('d-none');
|
||||
document.getElementById('resultsArea')?.classList.remove('d-none');
|
||||
|
||||
updateKPIs(data, payload.monthly_target);
|
||||
renderDetailedChart(data);
|
||||
renderTable(data);
|
||||
|
||||
} catch (err) {
|
||||
console.error("Simulation Error:", err);
|
||||
alert(`Analysis Failed: ${err.message}`);
|
||||
} finally {
|
||||
el.btn.disabled = false;
|
||||
el.btn.innerHTML = originalText;
|
||||
if (!payload.symbol) {
|
||||
alert("Please enter a ticker symbol.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Loading State
|
||||
el.btn.disabled = true;
|
||||
el.btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';
|
||||
|
||||
// We add ?t= + timestamp to the URL to bypass browser caching
|
||||
const res = await fetch(`/api/backtest?t=${new Date().getTime()}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `Server returned ${res.status}`);
|
||||
}
|
||||
|
||||
// Update UI
|
||||
document.getElementById('kpiArea')?.classList.remove('d-none');
|
||||
document.getElementById('resultsArea')?.classList.remove('d-none');
|
||||
|
||||
updateKPIs(data, payload.monthly_target);
|
||||
renderDetailedChart(data);
|
||||
renderTable(data);
|
||||
|
||||
} catch (err) {
|
||||
console.error("Simulation Error:", err);
|
||||
alert(`Analysis Failed: ${err.message}`);
|
||||
} finally {
|
||||
el.btn.disabled = false;
|
||||
el.btn.innerHTML = originalText;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Updates the summary cards with the DVA "Next Move" recommendation.
|
||||
@@ -247,40 +247,72 @@
|
||||
*/
|
||||
function updateKPIs(data, monthlyTarget) {
|
||||
if (!data || data.length === 0) return;
|
||||
|
||||
const last = data[data.length - 1];
|
||||
|
||||
// Helper function to update text ONLY if the element exists
|
||||
const safeUpdate = (id, value) => {
|
||||
// 1. Data Extraction (defined once to avoid VS Code red errors)
|
||||
const latestPrice = last.price || 0;
|
||||
const latestDate = last.date || "N/A";
|
||||
const nextMoveAmt = last.va_diff || 0;
|
||||
const sharesToMove = last.va_shares_trans || 0;
|
||||
const isNeg = nextMoveAmt < 0;
|
||||
const isPos = nextMoveAmt > 0;
|
||||
|
||||
// 2. Helper for standard KPI cards
|
||||
const setUI = (id, val) => {
|
||||
const el = document.getElementById(id);
|
||||
if (el) {
|
||||
el.innerText = value;
|
||||
} else {
|
||||
console.warn(`KPI Error: Element with ID '${id}' not found in HTML.`);
|
||||
}
|
||||
if (el) el.innerText = val;
|
||||
};
|
||||
|
||||
// 1. Format the values from the Python response
|
||||
const targetVal = (last.va_target_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
|
||||
const investedVal = (last.va_invested || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
|
||||
const marketVal = (last.va_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
|
||||
// Update the main 3 cards
|
||||
setUI('targetValueCard', `$${(last.va_target_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2})}`);
|
||||
setUI('totalSaved', `$${(last.va_invested || 0).toLocaleString(undefined, {minimumFractionDigits: 2})}`);
|
||||
setUI('totalVal', `$${(last.va_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2})}`);
|
||||
|
||||
// 2. Push to the UI using the IDs defined in the HTML above
|
||||
safeUpdate('targetValueCard', `$${targetVal}`);
|
||||
safeUpdate('totalSaved', `$${investedVal}`);
|
||||
safeUpdate('totalVal', `$${marketVal}`);
|
||||
|
||||
// 3. Update the Recommendation Card (Next Move)
|
||||
const nextMove = last.va_diff || 0;
|
||||
const nextAmtEl = document.getElementById('nextInvAmt');
|
||||
if (nextAmtEl) {
|
||||
nextAmtEl.innerText = (nextMove >= 0 ? "+" : "") + "$" + Math.abs(nextMove).toLocaleString();
|
||||
nextAmtEl.className = nextMove >= 0 ? "fw-bold text-success" : "fw-bold text-danger";
|
||||
// 3. Recommendation Card Logic (Background & Border)
|
||||
const recommendationCard = document.getElementById('nextMoveCard');
|
||||
if (recommendationCard) {
|
||||
if (isNeg) {
|
||||
recommendationCard.style.backgroundColor = "#fff5f5"; // Light Red
|
||||
recommendationCard.style.border = "2px solid #feb2b2";
|
||||
} else if (isPos) {
|
||||
recommendationCard.style.backgroundColor = "#f0fff4"; // Light Green
|
||||
recommendationCard.style.border = "2px solid #9ae6b4";
|
||||
} else {
|
||||
recommendationCard.style.backgroundColor = "#ffffff";
|
||||
recommendationCard.style.border = "1px solid #dee2e6";
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Update Move Amount & Color
|
||||
const amtEl = document.getElementById('nextInvAmt');
|
||||
if (amtEl) {
|
||||
amtEl.innerText = `${isNeg ? '-' : '+'}$${Math.abs(nextMoveAmt).toLocaleString(undefined, {minimumFractionDigits: 2})}`;
|
||||
amtEl.className = isNeg ? "fw-bold text-danger display-6" : "fw-bold text-success display-6";
|
||||
}
|
||||
|
||||
// 5. Update Action Message (Verb + Units)
|
||||
const msgEl = document.getElementById('nextInvMsg');
|
||||
if (msgEl) {
|
||||
const verb = isNeg ? "Sell" : "Buy";
|
||||
const colorClass = isNeg ? "text-danger" : "text-success";
|
||||
msgEl.innerHTML = `<span class="${colorClass} fw-bold">${verb}</span> <strong>${Math.abs(sharesToMove).toFixed(4)}</strong> units`;
|
||||
}
|
||||
|
||||
// 6. Update Footer Labels (Price & Date)
|
||||
const priceDisplay = document.getElementById('latestPriceDisplay');
|
||||
if (priceDisplay) {
|
||||
priceDisplay.innerText = `$${latestPrice.toLocaleString(undefined, {minimumFractionDigits: 2})}`;
|
||||
}
|
||||
|
||||
const dateDisplay = document.getElementById('priceDateLabel');
|
||||
if (dateDisplay) {
|
||||
dateDisplay.innerText = latestDate;
|
||||
}
|
||||
|
||||
// Optional: Sync Badge
|
||||
if (typeof updateSyncBadge === "function") updateSyncBadge(latestDate);
|
||||
}
|
||||
/**
|
||||
* Updates a visual badge showing if data is fresh or stale
|
||||
*/
|
||||
|
||||
function updateSyncBadge(dateString) {
|
||||
const syncDateEl = document.getElementById('lastSyncDate');
|
||||
const syncBadge = document.getElementById('syncBadge');
|
||||
|
||||
Reference in New Issue
Block a user