ADD more indictaors, BB,RSI and Z-score
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
Indicator,Visual Style,What it Means,Suggested Action
|
||||
Z-Score (60/120),Red Heatmap,Price is +2 standard deviations above the mean (Statistically overstretched).,SELL / TRIM (Take profits)
|
||||
Z-Score (60/120),Green Heatmap,Price is -2 standard deviations below the mean (Statistically depressed).,BUY / ACCUMULATE
|
||||
RSI,Red Bold Text,RSI is > 70. Momentum is extremely high/overbought.,CAUTION / HOLD (Don't buy new)
|
||||
RSI,Green Bold Text,RSI is < 30. Momentum is washed out/oversold.,WATCH FOR BOUNCE
|
||||
BB %B,Red Bold Text,Price is above the Upper Bollinger Band (>100%).,SELL / HEDGE
|
||||
BB %B,Green Bold Text,Price is below the Lower Bollinger Band (<0%).,WATCH FOR REVERSAL
|
||||
52W Range,Red Bar,Price is trading near its 1-year high.,RESISTANCE AREA
|
||||
52W Range,Green Bar,Price is trading near its 1-year low.,SUPPORT AREA
|
||||
Z-Score,Red Heatmap,Statistically 2σ above the mean.,SELL / TRIM (Take profits)
|
||||
Z-Score,Green Heatmap,Statistically 2σ below the mean.,BUY / ACCUMULATE
|
||||
RSI / BB,Red Text,Overbought (>70) or outside Upper Band.,CAUTION (Stop buying)
|
||||
RSI / BB,Green Text,Oversold (<30) or below Lower Band.,WATCH (Look for entry)
|
||||
Dist. to EMA,Percentage %,"How far the price is ""floating"" above/below its average.",MEAN REVERSION: High % usually leads to a pull-back to the line.
|
||||
KD (K/D),Value Pair,K > D: Bullish momentum. K < D: Bearish momentum.,"THE TRIGGER: Look for ""K"" crossing ""D"" to enter or exit."
|
||||
|
Binary file not shown.
Binary file not shown.
@@ -12,6 +12,11 @@ app = Flask(__name__)
|
||||
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})
|
||||
# The CSV is in the root directory (same level as app.py)
|
||||
CSV_PATH = os.path.join(os.path.dirname(__file__), 'instruments.csv')
|
||||
# This tells Flask it is behind a proxy and to trust the HTTPS headers from Synology
|
||||
@app.before_request
|
||||
def before_request():
|
||||
if request.headers.get('X-Forwarded-Proto') == 'https':
|
||||
request.environ['wsgi.url_scheme'] = 'https'
|
||||
|
||||
@app.route('/settings')
|
||||
def settings():
|
||||
|
||||
@@ -375,7 +375,39 @@ class DataEngine:
|
||||
prev_close = float(df.iloc[-2]['close'])
|
||||
change_pct = ((last_close - prev_close) / prev_close) * 100
|
||||
count = len(df)
|
||||
# --- NEW INDICATORS START ---
|
||||
|
||||
# Bollinger Bands %B (20-day)
|
||||
bb_pct = "N/A"
|
||||
if count >= 20:
|
||||
from ta.volatility import BollingerBands
|
||||
indicator_bb = BollingerBands(close=df['close'], window=20, window_dev=2)
|
||||
m_avg = indicator_bb.bollinger_mavg().iloc[-1]
|
||||
h_band = indicator_bb.bollinger_hband().iloc[-1]
|
||||
l_band = indicator_bb.bollinger_lband().iloc[-1]
|
||||
# Calculate %B: where is price relative to bands?
|
||||
if (h_band - l_band) != 0:
|
||||
bb_pct = round((last_close - l_band) / (h_band - l_band), 2)
|
||||
|
||||
# RSI (14-day)
|
||||
rsi_val = "N/A"
|
||||
if count >= 14:
|
||||
from ta.momentum import RSIIndicator
|
||||
rsi_val = round(RSIIndicator(close=df['close'], window=14).rsi().iloc[-1], 1)
|
||||
|
||||
# Z-Score Helper Function
|
||||
def get_z_score(window):
|
||||
if count >= window:
|
||||
rolling_mean = df['close'].rolling(window=window).mean()
|
||||
rolling_std = df['close'].rolling(window=window).std()
|
||||
z = (last_close - rolling_mean.iloc[-1]) / rolling_std.iloc[-1]
|
||||
return round(z, 2)
|
||||
return "N/A"
|
||||
|
||||
z60 = get_z_score(60)
|
||||
z120 = get_z_score(120)
|
||||
|
||||
# Existing EMA Logic (Distance % from EMA)
|
||||
def get_ema_offset(window):
|
||||
if count >= window:
|
||||
from ta.trend import EMAIndicator
|
||||
@@ -396,11 +428,15 @@ class DataEngine:
|
||||
|
||||
return {
|
||||
"symbol": self.symbol,
|
||||
"last_date": formatted_date, # <--- New field added
|
||||
"last_date": formatted_date,
|
||||
"last_close": round(last_close, 2),
|
||||
"change_pct": round(change_pct, 2),
|
||||
"low_52": round(float(df.tail(252)['close'].min()), 2),
|
||||
"high_52": round(float(df.tail(252)['close'].max()), 2),
|
||||
"bb_pct": bb_pct,
|
||||
"rsi": rsi_val,
|
||||
"z60": z60,
|
||||
"z120": z120,
|
||||
"last_ema20": get_ema_offset(20),
|
||||
"last_ema50": get_ema_offset(50),
|
||||
"last_ema100": get_ema_offset(100),
|
||||
|
||||
+75
-37
@@ -50,6 +50,7 @@
|
||||
}
|
||||
|
||||
.table {
|
||||
/*table-layout: fixed;
|
||||
/* table-layout: auto; */ /* Default - let it be auto for data safety */
|
||||
width: 100%;
|
||||
|
||||
@@ -82,6 +83,21 @@
|
||||
border-bottom: 1px solid #f1f1f1;
|
||||
padding: 10px 8px;
|
||||
}
|
||||
/* Price Trend Colors */
|
||||
.text-up { color: #28a745 !important; } /* Success Green */
|
||||
.text-down { color: #dc3545 !important; } /* Danger Red */
|
||||
|
||||
/* Table Cell Styling */
|
||||
#tableBody td {
|
||||
padding: 8px 4px;
|
||||
font-size: 0.85rem;
|
||||
white-space: nowrap;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
/* Custom heatmaps for Z-score */
|
||||
.bg-oversold { background-color: #d1e7dd !important; color: #0f5132 !important; }
|
||||
.bg-overbought { background-color: #f8d7da !important; color: #842029 !important; }
|
||||
|
||||
/* 3. Sticky Column Logic (Instrument) */
|
||||
.table td:first-child,
|
||||
@@ -210,7 +226,9 @@
|
||||
<div class="container-fluid p-0">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="mb-0 text-dark">Portfolio Signals</h5>
|
||||
<h5 class="mb-0 p-2 shadow-sm" style="background: linear-gradient(90deg, #007bff, #6610f2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: bold;">
|
||||
Portfolio Signals
|
||||
</h5>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span id="loading">Updating...</span>
|
||||
<button class="btn btn-outline-secondary btn-sm" onclick="loadData()">
|
||||
@@ -230,10 +248,14 @@
|
||||
<th style="min-width: 25px;">Date</th>
|
||||
<th style="min-width: 25px;">Close</th>
|
||||
<th style="min-width: 25px;">Chg%</th>
|
||||
<th style="min-width: 100px;">52W Range</th>
|
||||
<th style="min-width: 85px;">20 EMA</th>
|
||||
<th style="min-width: 25px;">50 EMA</th>
|
||||
<th style="min-width: 25px;">100 EMA</th>
|
||||
<th style="min-width: 25px;">L--52W--H</th>
|
||||
<th class="min-width: 50px;">RSI</th>
|
||||
<th class="min-width: 25px;">BB %B</th>
|
||||
<th class="min-width: 25px;">Z60</th>
|
||||
<th class="min-width: 25px;">Z120</th>
|
||||
<th style="min-width: 25px;">25 EMA%</th>
|
||||
<th style="min-width: 25px;">50 EMA%</th>
|
||||
<th style="min-width: 25px;">100 EMA%</th>
|
||||
<th style="min-width: 25px;">200 EMA</th>
|
||||
<th style="min-width: 60px;">K/D</th>
|
||||
</tr>
|
||||
@@ -267,8 +289,30 @@
|
||||
const colorClass = num >= 0 ? 'text-up' : 'text-down';
|
||||
return `<span class="${colorClass}">${sign}${num.toFixed(1)}%</span>`;
|
||||
};
|
||||
// Function for Z-Score (Heatmap style)
|
||||
const getZColor = (val) => {
|
||||
if (val === "N/A") return "";
|
||||
if (val >= 2) return 'style="background-color: #ffcccc; color: #cc0000; font-weight: bold;"'; // Overbought
|
||||
if (val <= -2) return 'style="background-color: #ccffcc; color: #006600; font-weight: bold;"'; // Oversold
|
||||
return "";
|
||||
};
|
||||
// Function for RSI (Text-only Traffic Ligh style)
|
||||
const getRSIColor = (val) => {
|
||||
if (val === "N/A") return "";
|
||||
if (val >= 70) return 'class="text-danger fw-bold"'; // Red Text
|
||||
if (val <= 30) return 'class="text-success fw-bold"'; // Green Text
|
||||
return "";
|
||||
};
|
||||
// Function for BB (Text-only Traffic Ligh style)
|
||||
const getBBColor = (val) => {
|
||||
if (val === "N/A" || val === null) return "";
|
||||
const numericVal = parseFloat(val);
|
||||
// Traffic Light Logic
|
||||
if (numericVal >= 1.0) return 'class="text-danger fw-bold"'; // Above Upper Band
|
||||
if (numericVal <= 0.0) return 'class="text-success fw-bold"'; // Below Lower Band
|
||||
return 'class="text-muted"'; // Neutral
|
||||
};
|
||||
|
||||
// --- 3. Load Table Data ---
|
||||
async function loadData() {
|
||||
console.log("Starting loadData...");
|
||||
const loading = document.getElementById('loading');
|
||||
@@ -279,49 +323,44 @@
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/summary');
|
||||
const result = await response.json(); // result is { last_sync: "...", data: [...] }
|
||||
const result = await response.json();
|
||||
|
||||
// 1. Update the Navbar Sync Time from Server
|
||||
// 1. Update Sync Time
|
||||
if (syncDisplay && result.last_sync) {
|
||||
syncDisplay.innerText = result.last_sync;
|
||||
syncDisplay.classList.add('text-success');
|
||||
setTimeout(() => syncDisplay.classList.remove('text-success'), 2000);
|
||||
}
|
||||
|
||||
// 2. Extract the instruments list
|
||||
const data = result.data;
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="10" class="p-4 text-center">No data found. Please run Sync.</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="14" class="p-4 text-center">No data found. Please run Sync.</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Prepare variables for the loop
|
||||
let htmlContent = '';
|
||||
const todayStr = new Date().toISOString().split('T')[0];
|
||||
|
||||
// 4. Loop through each item
|
||||
data.forEach(item => {
|
||||
// --- A. Error Row Handling ---
|
||||
// --- A. Error Handling ---
|
||||
if (item.error || !item.last_close || item.last_close === 'N/A') {
|
||||
htmlContent += `
|
||||
<tr>
|
||||
<td><div class="fw-bold text-muted">${item.name || item.symbol}</div></td>
|
||||
<td colspan="9" class="text-center p-3">
|
||||
<td colspan="13" class="text-center p-3">
|
||||
<span class="badge bg-warning text-dark">Needs Sync</span>
|
||||
<small class="text-muted ms-2">Local CSV not found or corrupted.</small>
|
||||
<small class="text-muted ms-2">Data not found or corrupted.</small>
|
||||
</td>
|
||||
</tr>`;
|
||||
return; // Skip to next item
|
||||
return;
|
||||
}
|
||||
|
||||
// --- B. Date & Style Calculations ---
|
||||
// --- B. Preparation & Math ---
|
||||
let displayDate = item.last_date || "N/A";
|
||||
let dateColor = '#dc3545'; // Default red for stale
|
||||
|
||||
let dateColor = '#dc3545';
|
||||
if (item.last_date && item.last_date.includes('-')) {
|
||||
const parts = item.last_date.split('-');
|
||||
displayDate = `${parts[2]}/${parts[1]}`; // DD/MM format
|
||||
displayDate = `${parts[2]}/${parts[1]}`;
|
||||
dateColor = (item.last_date === todayStr) ? '#28a745' : '#dc3545';
|
||||
}
|
||||
|
||||
@@ -329,23 +368,25 @@
|
||||
const low = parseFloat(item.low_52) || 0;
|
||||
const high = parseFloat(item.high_52) || 0;
|
||||
|
||||
// 52W Range Progress Bar
|
||||
// 52W Range calculation
|
||||
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');
|
||||
|
||||
// Freshness class for the badge
|
||||
// Indicators
|
||||
const rsiVal = item.rsi !== null ? item.rsi : "N/A";
|
||||
const bbRaw = parseFloat(item.bb_pct);
|
||||
const bbDisplay = !isNaN(bbRaw) ? (bbRaw * 100).toFixed(0) + '%' : 'N/A';
|
||||
const z60Val = item.z60 !== null ? item.z60 : "N/A";
|
||||
const z120Val = item.z120 !== null ? item.z120 : "N/A";
|
||||
|
||||
const isFresh = item.last_date === todayStr;
|
||||
const dateBadgeClass = isFresh ? 'badge bg-success-subtle text-success border border-success-subtle' : 'text-muted';
|
||||
|
||||
// --- C. Construct Row ---
|
||||
// --- C. Construct Row (14 Columns) ---
|
||||
htmlContent += `
|
||||
<tr>
|
||||
<td><div class="fw-bold">${item.name || item.symbol}</div></td>
|
||||
<td>
|
||||
<span class="${dateBadgeClass}" style="color: ${dateColor} !important; font-size: 0.75rem; padding: 2px 5px; border-radius: 4px;">
|
||||
${displayDate}
|
||||
</span>
|
||||
</td>
|
||||
<td><span class="table-date ${dateBadgeClass}" style="color: ${dateColor} !important;">${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}%
|
||||
@@ -358,6 +399,10 @@
|
||||
<div class="progress-bar bg-primary" style="width: ${rangePct}%"></div>
|
||||
</div>
|
||||
</td>
|
||||
<td ${getRSIColor(rsiVal)} class="text-center">${rsiVal}</td>
|
||||
<td ${getBBColor(item.bb_pct)} class="text-center">${bbDisplay}</td>
|
||||
<td ${getZColor(z60Val)} class="text-center">${z60Val}</td>
|
||||
<td ${getZColor(z120Val)} class="text-center">${z120Val}</td>
|
||||
<td>${typeof formatEma === 'function' ? formatEma(item.last_ema20) : item.last_ema20}</td>
|
||||
<td>${typeof formatEma === 'function' ? formatEma(item.last_ema50) : item.last_ema50}</td>
|
||||
<td>${typeof formatEma === 'function' ? formatEma(item.last_ema100) : item.last_ema100}</td>
|
||||
@@ -366,18 +411,11 @@
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
// 5. Final Injection
|
||||
tbody.innerHTML = htmlContent;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Fetch error:", error);
|
||||
if (syncDisplay) {
|
||||
syncDisplay.innerText = "OFFLINE";
|
||||
syncDisplay.classList.add('text-danger');
|
||||
}
|
||||
if (tbody) {
|
||||
tbody.innerHTML = '<tr><td colspan="10" class="text-danger p-4 text-center">Error loading summary. Check server logs.</td></tr>';
|
||||
}
|
||||
if (tbody) tbody.innerHTML = '<tr><td colspan="14" class="text-danger p-4 text-center">Error loading data.</td></tr>';
|
||||
} finally {
|
||||
if (loading) loading.style.display = 'none';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user