migo0722's picture
Update index.html
4f42e74 verified
Raw History Blame Contribute Delete
42.5 kB
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>台股正2動態槓桿表-蜈蚣長老模型</title>
<!-- 引入 Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- 引入 html2canvas 用於匯出圖片 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
body {
background-color: #f8f9fa;
font-family: "Helvetica Neue", Helvetica, Arial, "微軟正黑體", sans-serif;
}
.card-header {
background-color: #0d6efd;
color: white;
font-weight: bold;
}
th, td {
vertical-align: middle;
white-space: nowrap;
}
.action-col {
white-space: normal;
min-width: 280px;
}
/* 凍結第一欄:點位 (提升手機版體驗) */
.table-responsive {
overflow-x: auto;
}
th:first-child, td:first-child {
position: sticky;
left: 0;
z-index: 2;
background-color: inherit;
border-right: 2px solid #dee2e6;
}
thead th:first-child {
background-color: #f8f9fa !important;
}
/* 自訂表格高亮顏色 */
.table-orange-custom td {
background-color: #fff0db !important;
font-weight: bold;
box-shadow: inset 0 0 0 9999px #fff0db !important;
}
.table-blue-custom td {
background-color: #e8f4ff !important;
font-weight: bold;
box-shadow: inset 0 0 0 9999px #e8f4ff !important;
}
/* 圖例標籤樣式 */
.legend-orange {
background-color: #fff0db;
border: 1px solid #ffd8a8;
padding: 2px 8px;
border-radius: 4px;
color: #995500;
}
.legend-blue {
background-color: #e8f4ff;
border: 1px solid #b6d4fe;
padding: 2px 8px;
border-radius: 4px;
color: #052c65;
}
/* 漲跌幅文字顏色 */
.text-up { color: #dc3545; }
.text-down { color: #198754; }
/* 維持率警示標籤 */
.badge-warning-custom { background-color: #ffc107; color: #000; padding: 4px 8px; border-radius: 4px;}
.badge-danger-custom { background-color: #dc3545; color: #fff; padding: 4px 8px; border-radius: 4px;}
</style>
</head>
<body>
<div class="container my-4">
<h2 class="text-center mb-4">台股正2動態槓桿表 <span class="badge bg-secondary fs-6">動態估值模型</span></h2>
<!-- 輸入參數區 -->
<div class="card mb-4 shadow-sm">
<div class="card-header fs-5">
投資部位與模型參數設定
</div>
<div class="card-body">
<form id="calcForm">
<div class="row g-3">
<!-- 行情自動抓取與手動點位輸入區 -->
<div class="col-md-4 col-sm-6">
<label class="form-label d-flex justify-content-between align-items-center">
<span>目前加權指數點位:</span>
</label>
<div class="input-group">
<input type="number" class="form-control" id="entry_index" value="23000" step="any" required>
<button class="btn btn-outline-primary" type="button" id="btn_fetch_index" onclick="fetchTwseIndex()">
🔄 取得最新
</button>
</div>
<div id="index_fetch_status" class="form-text text-muted" style="font-size: 0.82rem;">
準備載入最新行情...
</div>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">正2持股市值(萬):</label>
<input type="number" class="form-control" id="entry_stock" value="132" step="any" required>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">現金儲備(萬):</label>
<input type="number" class="form-control" id="entry_cash" value="132" step="any" required>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">既有質押借款(萬):</label>
<input type="number" class="form-control" id="entry_debt" value="0" step="any" required>
</div>
<!-- 階梯設定 -->
<div class="col-md-4 col-sm-6">
<div class="d-flex justify-content-between align-items-center mb-2">
<label class="form-label mb-0">網格階梯(再平衡)基準:</label>
<div class="btn-group btn-group-sm" role="group">
<input type="radio" class="btn-check" name="step_type" id="step_type_point" value="point" onchange="toggleStepType()">
<label class="btn btn-outline-primary py-0 px-2" for="step_type_point">點數</label>
<input type="radio" class="btn-check" name="step_type" id="step_type_pct" value="percent" checked onchange="toggleStepType()">
<label class="btn btn-outline-primary py-0 px-2" for="step_type_pct">漲跌%</label>
</div>
</div>
<!-- 依點數設定 -->
<div id="step_point_container" style="display: none;">
<div class="input-group">
<input type="number" class="form-control" id="entry_step" value="2000" step="any" placeholder="例如: 2000">
<span class="input-group-text">點</span>
</div>
</div>
<!-- 依百分比設定 -->
<div id="step_pct_container">
<select class="form-select" id="entry_pct_step" onchange="calculateGrid()">
<option value="0.05">漲跌 5%</option>
<option value="0.10" selected>漲跌 10%</option>
<option value="0.15">漲跌 15%</option>
<option value="0.20">漲跌 20%</option>
<option value="0.25">漲跌 25%</option>
<option value="0.30">漲跌 30%</option>
<option value="0.35">漲跌 35%</option>
<option value="0.40">漲跌 40%</option>
<option value="0.45">漲跌 45%</option>
<option value="0.50">漲跌 50%</option>
</select>
</div>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">全市場預估 EPS:</label>
<input type="number" class="form-control" id="entry_eps" value="1754" step="any" required>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">最高網格指數(自訂上限):</label>
<input type="number" class="form-control" id="entry_max_idx" value="50000" step="any" required>
</div>
<div class="col-md-4 col-sm-6">
<label class="form-label">最低網格指數(自訂下限):</label>
<input type="number" class="form-control" id="entry_min_idx" value="16000" step="any" required>
</div>
<div class="col-md-4 col-sm-12 d-flex align-items-end">
<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" id="var_pledge" onchange="onPledgeToggle()">
<label class="form-check-label fs-6 fw-bold" for="var_pledge">
允許質押借貸模式 (槓桿可提升至 3.0x+)
</label>
</div>
</div>
<!-- 藍色帶模型估值範圍設定區 -->
<div class="col-12 mt-3 pt-3 border-top">
<div class="d-flex flex-wrap justify-content-between align-items-center mb-2">
<label class="form-label fw-bold mb-0">藍色帶估值與槓桿範圍模式:</label>
<div class="btn-group btn-group-sm" role="group">
<input type="radio" class="btn-check" name="range_mode" id="range_mode_elder" value="elder" checked onchange="toggleRangeMode()">
<label class="btn btn-outline-primary" for="range_mode_elder">蜈蚣長老標準模型</label>
<input type="radio" class="btn-check" name="range_mode" id="range_mode_custom" value="custom" onchange="toggleRangeMode()">
<label class="btn btn-outline-primary" for="range_mode_custom">使用者自訂範圍</label>
</div>
</div>
<!-- 長老標準範圍說明區 -->
<div id="elder_info_container" class="alert alert-primary py-2 px-3 mb-0 small">
<strong>長老標準模型參數:</strong>
估值上限 <strong>47,580 點</strong> (1.6x 槓桿) | 質押轉折 <strong>43,920 點</strong> (2.0x 槓桿) | 質押滿槓 <strong>34,770 點</strong> (3.0x 槓桿) | 無質押滿倉 <strong>34,000 點</strong> (2.0x 槓桿)。
</div>
<!-- 使用者自訂點位輸入區 -->
<div id="custom_range_container" class="row g-2 p-2 bg-light rounded border mt-1" style="display: none;">
<div class="col-md-4 col-sm-6">
<label class="form-label small fw-bold mb-1">自訂估值上限 (1.6x 槓桿):</label>
<div class="input-group input-group-sm">
<input type="number" class="form-control" id="custom_p_1_6x" value="28000" step="100" onchange="calculateGrid()">
<span class="input-group-text">點</span>
</div>
<div class="form-text text-muted" style="font-size: 0.75rem;">抵達或高於此點位,槓桿降至 1.6x</div>
</div>
<!-- 質押啟用時的 2.0x 轉折點 -->
<div class="col-md-4 col-sm-6" id="custom_pledge_turn_col">
<label class="form-label small fw-bold mb-1">自訂質押啟動點 (2.0x 槓桿):</label>
<div class="input-group input-group-sm">
<input type="number" class="form-control" id="custom_p_2_0x" value="24000" step="100" onchange="calculateGrid()">
<span class="input-group-text">點</span>
</div>
<div class="form-text text-muted" style="font-size: 0.75rem;">現金耗盡、開始質押借款的轉折點</div>
</div>
<!-- 質押啟用時的 3.0x 滿槓點 -->
<div class="col-md-4 col-sm-6" id="custom_pledge_low_col">
<label class="form-label small fw-bold mb-1">自訂質押滿槓點 (3.0x 槓桿):</label>
<div class="input-group input-group-sm">
<input type="number" class="form-control" id="custom_p_3_0x" value="19000" step="100" onchange="calculateGrid()">
<span class="input-group-text">點</span>
</div>
<div class="form-text text-muted" style="font-size: 0.75rem;">借款達 3.0x 目標之估值下限</div>
</div>
<!-- 無質押時的 2.0x 滿倉點 -->
<div class="col-md-4 col-sm-6" id="custom_no_pledge_low_col" style="display: none;">
<label class="form-label small fw-bold mb-1">自訂估值下限 (2.0x 滿倉):</label>
<div class="input-group input-group-sm">
<input type="number" class="form-control" id="custom_no_pledge_2_0x" value="19000" step="100" onchange="calculateGrid()">
<span class="input-group-text">點</span>
</div>
<div class="form-text text-muted" style="font-size: 0.75rem;">現金全數買進正二滿倉之估值下限</div>
</div>
</div>
</div>
</div>
<div class="mt-4 text-center">
<button type="button" class="btn btn-primary btn-lg w-100 w-md-auto px-5" onclick="calculateGrid()">生成動態操作表</button>
</div>
</form>
</div>
</div>
<!-- 表格結果區 -->
<div class="card shadow-sm" id="exportArea">
<div class="card-body p-3">
<!-- 頂部:說明區與匯出工具列 -->
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-3 gap-2">
<div class="text-secondary fs-6">
💡 <strong>圖例說明:</strong>
<span class="legend-orange fw-bold me-1">淺橘</span> 當前現況,
<span class="legend-blue fw-bold me-1">淺藍</span> <span id="legend_range_desc">模型標準估算範圍</span>,
<span class="bg-light border px-2 py-1 rounded text-dark">無底色</span> 自訂延伸推算。
<br><small class="text-muted mt-1 d-block">(註:操作指引皆預設為抵達該點位時的「連續」推算路徑)</small>
</div>
<div class="d-flex gap-2" data-html2canvas-ignore="true">
<button type="button" class="btn btn-outline-success btn-sm" onclick="exportToCSV()">
📊 匯出 CSV
</button>
<button type="button" class="btn btn-outline-danger btn-sm" onclick="exportToImage()">
📸 匯出圖片
</button>
</div>
</div>
<!-- 表格本體 -->
<div class="table-responsive bg-white rounded" style="border: 1px solid #dee2e6;">
<table class="table table-bordered table-hover mb-0 text-center" id="dataTable">
<thead class="table-light">
<tr>
<th>點位</th>
<th>距現況漲跌幅</th>
<th>P/E</th>
<th>目標槓桿</th>
<th>實際槓桿</th>
<th>動態淨值(NAV)</th>
<th>正2持股市值</th>
<th class="table-success">現金餘額</th>
<th class="table-danger">質押借款</th>
<th>維持率</th>
<th class="action-col">階梯觸發操作指引</th>
</tr>
</thead>
<tbody id="resultBody">
<!-- JS 渲染結果區 -->
</tbody>
</table>
</div>
<!-- 底部:免責提示與右下角版本控制時間戳記 -->
<div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mt-3 pt-2 border-top text-muted" style="font-size: 0.82rem;">
<span class="fst-italic">※ 試算結果僅供策略模擬與資產再平衡對照,投資請審慎評估風險</span>
<span class="mt-1 mt-sm-0 text-end">
版本標記:<strong id="versionTimestamp" class="font-monospace text-dark">--</strong>
</span>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// --- 取得當前時間字串:年.月.日_時:分 ---
function getFormattedTimestamp() {
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const hh = String(now.getHours()).padStart(2, '0');
const min = String(now.getMinutes()).padStart(2, '0');
return `${yyyy}.${mm}.${dd}_${hh}:${min}`;
}
function updateVersionDisplay() {
const tsEl = document.getElementById('versionTimestamp');
if (tsEl) {
tsEl.textContent = getFormattedTimestamp();
}
}
// --- LocalStorage 儲存與讀取功能 ---
function saveParams() {
const inputs = [
'entry_index', 'entry_stock', 'entry_cash', 'entry_debt',
'entry_step', 'entry_pct_step', 'entry_eps', 'entry_max_idx', 'entry_min_idx',
'custom_p_1_6x', 'custom_p_2_0x', 'custom_p_3_0x', 'custom_no_pledge_2_0x'
];
inputs.forEach(id => {
const el = document.getElementById(id);
if (el) localStorage.setItem(id, el.value);
});
const checkedStep = document.querySelector('input[name="step_type"]:checked');
if (checkedStep) localStorage.setItem('step_type', checkedStep.value);
const checkedRange = document.querySelector('input[name="range_mode"]:checked');
if (checkedRange) localStorage.setItem('range_mode', checkedRange.value);
const pledgeEl = document.getElementById('var_pledge');
if (pledgeEl) localStorage.setItem('var_pledge', pledgeEl.checked);
}
function loadParams() {
const inputs = [
'entry_index', 'entry_stock', 'entry_cash', 'entry_debt',
'entry_step', 'entry_pct_step', 'entry_eps', 'entry_max_idx', 'entry_min_idx',
'custom_p_1_6x', 'custom_p_2_0x', 'custom_p_3_0x', 'custom_no_pledge_2_0x'
];
inputs.forEach(id => {
if(localStorage.getItem(id) !== null) {
const el = document.getElementById(id);
if (el) el.value = localStorage.getItem(id);
}
});
if(localStorage.getItem('step_type') !== null) {
let st = localStorage.getItem('step_type');
const radioEl = document.getElementById(st === 'point' ? 'step_type_point' : 'step_type_pct');
if (radioEl) radioEl.checked = true;
}
if(localStorage.getItem('range_mode') !== null) {
let rm = localStorage.getItem('range_mode');
const radioEl = document.getElementById(rm === 'custom' ? 'range_mode_custom' : 'range_mode_elder');
if (radioEl) radioEl.checked = true;
}
if(localStorage.getItem('var_pledge') !== null) {
const pEl = document.getElementById('var_pledge');
if (pEl) pEl.checked = localStorage.getItem('var_pledge') === 'true';
}
toggleStepType();
toggleRangeMode();
}
document.querySelectorAll('input, select').forEach(el => el.addEventListener('change', saveParams));
// 切換階梯基準
function toggleStepType() {
const stepType = document.querySelector('input[name="step_type"]:checked').value;
const pointContainer = document.getElementById('step_point_container');
const pctContainer = document.getElementById('step_pct_container');
if (stepType === 'point') {
pointContainer.style.display = 'block';
pctContainer.style.display = 'none';
} else {
pointContainer.style.display = 'none';
pctContainer.style.display = 'block';
}
calculateGrid();
saveParams();
}
// 切換長老模型 vs 自訂範圍
function toggleRangeMode() {
const rangeMode = document.querySelector('input[name="range_mode"]:checked').value;
const elderInfo = document.getElementById('elder_info_container');
const customContainer = document.getElementById('custom_range_container');
if (rangeMode === 'elder') {
elderInfo.style.display = 'block';
customContainer.style.display = 'none';
} else {
elderInfo.style.display = 'none';
customContainer.style.display = 'flex';
}
updateCustomFieldsByPledge();
calculateGrid();
saveParams();
}
// 質押勾選狀態改變時連動
function onPledgeToggle() {
updateCustomFieldsByPledge();
calculateGrid();
saveParams();
}
function updateCustomFieldsByPledge() {
const allowPledge = document.getElementById('var_pledge').checked;
const pledgeTurnCol = document.getElementById('custom_pledge_turn_col');
const pledgeLowCol = document.getElementById('custom_pledge_low_col');
const noPledgeLowCol = document.getElementById('custom_no_pledge_low_col');
if (allowPledge) {
if (pledgeTurnCol) pledgeTurnCol.style.display = 'block';
if (pledgeLowCol) pledgeLowCol.style.display = 'block';
if (noPledgeLowCol) noPledgeLowCol.style.display = 'none';
} else {
if (pledgeTurnCol) pledgeTurnCol.style.display = 'none';
if (pledgeLowCol) pledgeLowCol.style.display = 'none';
if (noPledgeLowCol) noPledgeLowCol.style.display = 'block';
}
}
// 動態槓桿比計算 (支援長老模型與自訂錨點)
function getTargetLeverage(idx, allowPledge, anchors) {
const { p_1_6x, p_2_0x, p_3_0x, no_pledge_2_0x } = anchors;
if (!allowPledge) {
if (idx >= p_1_6x) return 1.6;
else if (idx <= no_pledge_2_0x) return 2.0;
else {
let range = Math.max(1, p_1_6x - no_pledge_2_0x);
return 2.0 - ((idx - no_pledge_2_0x) / range) * (2.0 - 1.6);
}
} else {
if (idx >= p_1_6x) return 1.6;
else if (idx >= p_2_0x) {
let range = Math.max(1, p_1_6x - p_2_0x);
return 2.0 - ((idx - p_2_0x) / range) * (2.0 - 1.6);
} else if (idx >= p_3_0x) {
let range = Math.max(1, p_2_0x - p_3_0x);
return 3.0 - ((idx - p_3_0x) / range) * (3.0 - 2.0);
} else {
let range = Math.max(1, p_2_0x - p_3_0x);
let lev = 3.0 + ((p_3_0x - idx) / range) * 0.2;
return Math.min(3.2, lev);
}
}
}
// --- 強化版:多線路與雙數據源連線取得最新加權指數 ---
async function fetchTwseIndex() {
const btn = document.getElementById('btn_fetch_index');
const statusEl = document.getElementById('index_fetch_status');
const indexInput = document.getElementById('entry_index');
if (btn) btn.disabled = true;
if (statusEl) {
statusEl.innerHTML = `<span class="spinner-border spinner-border-sm text-primary" role="status"></span> 連線行情中...`;
}
const fetchWithTimeout = async (url, timeoutMs = 4500) => {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, { signal: controller.signal, cache: 'no-store' });
clearTimeout(id);
return res;
} catch (err) {
clearTimeout(id);
throw err;
}
};
const proxyWrappers = [
url => `https://corsproxy.io/?url=${encodeURIComponent(url)}`,
url => `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
url => `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(url)}`
];
let latestPrice = null;
let updateTime = "";
let sourceName = "";
// 策略 1: 優先嘗試 Yahoo Finance (^TWII 大盤指數)
const yahooTarget = `https://query1.finance.yahoo.com/v8/finance/chart/%5ETWII?interval=1d&range=1d&_=${Date.now()}`;
for (let getProxyUrl of proxyWrappers) {
try {
const res = await fetchWithTimeout(getProxyUrl(yahooTarget), 4000);
if (res.ok) {
const data = await res.json();
const meta = data?.chart?.result?.[0]?.meta;
if (meta && (meta.regularMarketPrice || meta.chartPreviousClose)) {
latestPrice = meta.regularMarketPrice || meta.chartPreviousClose;
let d = meta.regularMarketTime ? new Date(meta.regularMarketTime * 1000) : new Date();
updateTime = `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
sourceName = "Yahoo 行情";
break;
}
}
} catch (e) {
continue;
}
}
// 策略 2: 若 Yahoo 失敗,嘗試證交所 MIS 即時報價
if (latestPrice === null) {
const twseTarget = `https://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_t00.tw&_=${Date.now()}`;
for (let getProxyUrl of proxyWrappers) {
try {
const res = await fetchWithTimeout(getProxyUrl(twseTarget), 4000);
if (res.ok) {
const data = await res.json();
if (data?.msgArray?.length > 0) {
const item = data.msgArray[0];
let val = parseFloat(item.z);
if (isNaN(val) || val <= 0) val = parseFloat(item.y);
if (!isNaN(val) && val > 0) {
latestPrice = val;
updateTime = item.t || "最新收盤";
sourceName = "證交所 MIS";
break;
}
}
}
} catch (e) {
continue;
}
}
}
// 處理抓取結果
if (latestPrice !== null && !isNaN(latestPrice)) {
const roundedPrice = Math.round(latestPrice);
indexInput.value = roundedPrice;
if (statusEl) {
statusEl.innerHTML = `<span class="text-success fw-bold">✔ 已更新: ${roundedPrice.toLocaleString()} 點 <small class="text-muted">(${sourceName} ${updateTime})</small></span>`;
}
saveParams();
calculateGrid();
} else {
if (statusEl) {
statusEl.innerHTML = `<span class="text-danger">⚠️ 行情連線受限,已保留現有點位 (請手動輸入)</span>`;
}
}
if (btn) btn.disabled = false;
}
function getActionText(stock_val, target_stock, prev_cash, prev_debt, new_cash, new_debt, hitMaxDebt) {
let action_stock = target_stock - stock_val;
let text = "";
if (Math.abs(action_stock) < 0.01) return "維持部位不變";
if (action_stock > 0) {
let used_cash = prev_cash - new_cash;
let added_debt = new_debt - prev_debt;
let details = [];
if (used_cash > 0.01) details.push(`消耗現金 ${used_cash.toFixed(2)} 萬`);
if (added_debt > 0.01) details.push(`新增借款 ${added_debt.toFixed(2)} 萬`);
text = `買進正二 ${action_stock.toFixed(2)} 萬`;
if (details.length > 0) text += ` (${details.join(",")})`;
} else {
let sell_amt = Math.abs(action_stock);
let paid_debt = prev_debt - new_debt;
let added_cash = new_cash - prev_cash;
let details = [];
if (paid_debt > 0.01) details.push(`償還借款 ${paid_debt.toFixed(2)} 萬`);
if (added_cash > 0.01) details.push(`轉現金 ${added_cash.toFixed(2)} 萬`);
text = `賣出正二 ${sell_amt.toFixed(2)} 萬`;
if (details.length > 0) text += ` (${details.join(",")})`;
}
if (hitMaxDebt) text += ` <span class="badge bg-danger ms-1">⚠️已達質押60%上限</span>`;
return text;
}
function getMaintenanceStr(stock, debt) {
if (debt <= 0) return "無借款";
let m_ratio = (stock / debt) * 100;
if (m_ratio < 130) return `<span class="badge-danger-custom fw-bold">${m_ratio.toFixed(0)}% (斷頭)</span>`;
if (m_ratio < 166) return `<span class="badge-warning-custom fw-bold">${m_ratio.toFixed(0)}% (警戒)</span>`;
return `${m_ratio.toFixed(0)}%`;
}
function fmtIdx(num) { return Math.round(num).toLocaleString('en-US'); }
function formatPctChange(cur_idx, base_idx) {
if (base_idx === 0) return { text: "0.0%", class: "" };
let pct = ((cur_idx - base_idx) / base_idx) * 100;
if (Math.abs(pct) < 0.01) return { text: "0.0%", class: "" };
else if (pct > 0) return { text: `+${pct.toFixed(1)}%`, class: "text-up fw-bold" };
else return { text: `${pct.toFixed(1)}%`, class: "text-down fw-bold" };
}
function calculateGrid() {
const cur_index = parseFloat(document.getElementById('entry_index').value);
const cur_stock = parseFloat(document.getElementById('entry_stock').value);
const cur_cash = parseFloat(document.getElementById('entry_cash').value);
const cur_debt = parseFloat(document.getElementById('entry_debt').value);
const eps = parseFloat(document.getElementById('entry_eps').value);
const max_idx = parseFloat(document.getElementById('entry_max_idx').value);
const min_idx = parseFloat(document.getElementById('entry_min_idx').value);
const allow_pledge = document.getElementById('var_pledge').checked;
const step_type = document.querySelector('input[name="step_type"]:checked').value;
const range_mode = document.querySelector('input[name="range_mode"]:checked').value;
// 更新版本時間戳記
updateVersionDisplay();
let step_val = 0, pct_val = 0;
if (step_type === 'point') {
step_val = parseFloat(document.getElementById('entry_step').value);
if (isNaN(step_val) || step_val <= 0) return;
} else {
pct_val = parseFloat(document.getElementById('entry_pct_step').value);
}
// 決定模型錨點 (長老標準 vs 自訂)
let anchors = {};
if (range_mode === 'elder') {
anchors = {
p_1_6x: 47580,
p_2_0x: 43920,
p_3_0x: 34770,
no_pledge_2_0x: 34000
};
} else {
anchors = {
p_1_6x: parseFloat(document.getElementById('custom_p_1_6x').value) || 28000,
p_2_0x: parseFloat(document.getElementById('custom_p_2_0x').value) || 24000,
p_3_0x: parseFloat(document.getElementById('custom_p_3_0x').value) || 19000,
no_pledge_2_0x: parseFloat(document.getElementById('custom_no_pledge_2_0x').value) || 19000
};
}
// 藍色帶邊界判斷
const band_max = anchors.p_1_6x;
const band_min = allow_pledge ? anchors.p_3_0x : anchors.no_pledge_2_0x;
// 更新圖例說明字樣
const legendDesc = document.getElementById('legend_range_desc');
if (legendDesc) {
legendDesc.innerHTML = `${range_mode === 'elder' ? '長老模型標準估算範圍' : '自訂估算範圍'} (${fmtIdx(band_min)} ~ ${fmtIdx(band_max)})`;
}
if (isNaN(cur_index) || isNaN(cur_stock) || isNaN(cur_cash) || isNaN(cur_debt) || isNaN(eps) || isNaN(max_idx) || isNaN(min_idx)) return;
if (max_idx <= cur_index || min_idx >= cur_index) return;
const tbody = document.getElementById('resultBody');
tbody.innerHTML = "";
const init_nav = cur_stock + cur_cash - cur_debt;
// --- 基準點 (顯示使用者當下輸入的數值) ---
let actual_lev_base = init_nav > 0 ? (cur_stock * 2) / init_nav : 0;
let target_lev_base = getTargetLeverage(cur_index, allow_pledge, anchors);
let ideal_stock_base = init_nav * (target_lev_base / 2.0);
let gap = ideal_stock_base - cur_stock;
let base_act = "";
if (Math.abs(gap) > 1.0) {
if (gap > 0) base_act = `當前狀態: 槓桿低於目標 (${target_lev_base.toFixed(2)}x),建議逢低補進約 ${gap.toFixed(2)} 萬`;
else base_act = `當前狀態: 槓桿高於目標 (${target_lev_base.toFixed(2)}x),建議適度減碼約 ${Math.abs(gap).toFixed(2)} 萬`;
} else {
base_act = "當前狀態: 部位符合模型,維持現狀";
}
const baseRowData = {
idx: cur_index, pe: cur_index / eps, t_lev: target_lev_base, a_lev: actual_lev_base,
nav: init_nav, stock: cur_stock, cash: cur_cash, debt: cur_debt,
m_str: getMaintenanceStr(cur_stock, cur_debt),
act: base_act, isBase: true,
isInRange: (cur_index <= band_max + 0.01 && cur_index >= band_min - 0.01)
};
function calculateStep(prev_stock, prev_cash, prev_debt, prev_idx, target_idx) {
let r = (target_idx - prev_idx) / prev_idx;
let stock_val = prev_stock * (1.0 + 2.0 * r);
let nav = stock_val + prev_cash - prev_debt;
let target_lev = getTargetLeverage(target_idx, allow_pledge, anchors);
let ideal_stock = nav * (target_lev / 2.0);
let action_amt = ideal_stock - stock_val;
let target_stock = ideal_stock;
let new_cash = prev_cash;
let new_debt = prev_debt;
let hitMaxDebt = false;
if (action_amt > 0) { // 買進
if (new_cash >= action_amt) {
new_cash -= action_amt;
} else {
let shortfall = action_amt - new_cash;
new_cash = 0;
new_debt += shortfall;
let max_debt = nav * 0.60;
if (new_debt > max_debt) {
let allowed_extra_debt = max_debt - prev_debt;
let max_buy = prev_cash + Math.max(0, allowed_extra_debt);
target_stock = stock_val + max_buy;
new_debt = max_debt;
hitMaxDebt = true;
}
}
} else if (action_amt < 0) { // 賣出
let sell_amt = Math.abs(action_amt);
if (new_debt >= sell_amt) {
new_debt -= sell_amt;
} else {
let surplus = sell_amt - new_debt;
new_debt = 0;
new_cash += surplus;
}
}
let act = getActionText(stock_val, target_stock, prev_cash, prev_debt, new_cash, new_debt, hitMaxDebt);
return {
idx: target_idx, pe: target_idx / eps, t_lev: target_lev, a_lev: (target_stock * 2) / nav,
nav, stock: target_stock, cash: new_cash, debt: new_debt,
m_str: getMaintenanceStr(target_stock, new_debt),
act, isBase: false,
isInRange: (target_idx <= band_max + 0.01 && target_idx >= band_min - 0.01)
};
}
// --- 向上階梯 ---
let up_targets = [];
let current_up = cur_index;
while (true) {
let next_up = step_type === 'point' ? current_up + step_val : Math.round(current_up * (1 + pct_val));
if (next_up > max_idx) break;
up_targets.push(next_up);
current_up = next_up;
}
let up_rows = [];
let p_stock = cur_stock, p_cash = cur_cash, p_debt = cur_debt, p_idx = cur_index;
for (let idx of up_targets) {
let res = calculateStep(p_stock, p_cash, p_debt, p_idx, idx);
up_rows.push(res);
p_stock = res.stock; p_cash = res.cash; p_debt = res.debt; p_idx = idx;
}
// --- 向下階梯 ---
let down_targets = [];
let current_down = cur_index;
while (true) {
let next_down = step_type === 'point' ? current_down - step_val : Math.round(current_down * (1 - pct_val));
if (next_down < min_idx) break;
down_targets.push(next_down);
current_down = next_down;
}
let down_rows = [];
p_stock = cur_stock; p_cash = cur_cash; p_debt = cur_debt; p_idx = cur_index;
for (let idx of down_targets) {
let res = calculateStep(p_stock, p_cash, p_debt, p_idx, idx);
down_rows.push(res);
p_stock = res.stock; p_cash = res.cash; p_debt = res.debt; p_idx = idx;
}
// --- 渲染表格 ---
let allData = [];
up_rows.reverse().forEach(row => allData.push(row));
allData.push(baseRowData);
down_rows.forEach(row => allData.push(row));
allData.forEach(row => {
let tr = document.createElement('tr');
if (row.isBase) tr.className = "table-orange-custom";
else if (row.isInRange) tr.className = "table-blue-custom";
let pctObj = formatPctChange(row.idx, cur_index);
let debtHtml = row.debt === 0 ? '-' : `<span class="text-danger fw-bold">${row.debt.toFixed(2)} 萬</span>`;
let cashHtml = row.cash === 0 ? '-' : `<span class="text-success fw-bold">${row.cash.toFixed(2)} 萬</span>`;
tr.innerHTML = `
<td>${fmtIdx(row.idx)}</td>
<td class="${pctObj.class}">${pctObj.text}</td>
<td>${row.pe.toFixed(2)}x</td>
<td>${row.t_lev.toFixed(2)}x</td>
<td>${row.a_lev.toFixed(2)}x</td>
<td>${row.nav.toFixed(2)} 萬</td>
<td>${row.stock.toFixed(2)} 萬</td>
<td>${cashHtml}</td>
<td>${debtHtml}</td>
<td>${row.m_str}</td>
<td class="action-col text-start">${row.act}</td>
`;
tbody.appendChild(tr);
});
}
function exportToCSV() {
const timestamp = getFormattedTimestamp();
let table = document.getElementById("dataTable");
let rows = table.querySelectorAll("tr");
let csv = [];
// CSV 首行加入版本資訊
csv.push(`"台股正2動態槓桿表","產表時間: ${timestamp}"`);
csv.push("");
for (let i = 0; i < rows.length; i++) {
let row = [], cols = rows[i].querySelectorAll("td, th");
for (let j = 0; j < cols.length; j++) {
let tempDiv = document.createElement("div");
tempDiv.innerHTML = cols[j].innerHTML;
let data = tempDiv.textContent || tempDiv.innerText || "";
data = data.replace(/"/g, '""').trim();
row.push('"' + data + '"');
}
csv.push(row.join(","));
}
let csvContent = "\uFEFF" + csv.join("\n");
let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
let url = URL.createObjectURL(blob);
let link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `台股正2_動態槓桿表_${timestamp.replace(':', '')}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function exportToImage() {
// 匯出前強制刷新當下時間戳記
updateVersionDisplay();
const timestamp = getFormattedTimestamp();
const exportArea = document.getElementById('exportArea');
exportArea.style.boxShadow = "none";
const stickies = document.querySelectorAll('th:first-child, td:first-child');
stickies.forEach(el => el.style.position = 'static');
html2canvas(exportArea, {
scale: 2,
backgroundColor: "#ffffff",
useCORS: true
}).then(canvas => {
let link = document.createElement('a');
link.download = `台股正2_動態槓桿表_${timestamp.replace(':', '')}.png`;
link.href = canvas.toDataURL("image/png");
link.click();
exportArea.style.boxShadow = "";
stickies.forEach(el => el.style.position = 'sticky');
});
}
window.onload = function() {
loadParams();
calculateGrid();
fetchTwseIndex();
};
</script>
</body>
</html>