Spaces:
Sleeping
Sleeping
Integrated live FastAPI backend endpoints with Dashboard, replacing mock data with localStorage state and dynamic analytics
Browse files- backend/app.py +67 -0
- backend/reliability_scoring.py +15 -14
- frontend/app.js +3 -0
- frontend/dashboard.html +11 -1
- frontend/dashboard.js +128 -98
backend/app.py
CHANGED
|
@@ -15,6 +15,7 @@ from trader import (
|
|
| 15 |
add_to_balance, withdraw_from_balance, get_wallet_transactions,
|
| 16 |
get_value_history,
|
| 17 |
)
|
|
|
|
| 18 |
import concurrent.futures
|
| 19 |
|
| 20 |
app = FastAPI(title="StockSense AI", version="3.0.0")
|
|
@@ -697,3 +698,69 @@ def portfolio_value_history():
|
|
| 697 |
return {"snapshots": snapshots, "status": "success"}
|
| 698 |
except Exception as e:
|
| 699 |
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
add_to_balance, withdraw_from_balance, get_wallet_transactions,
|
| 16 |
get_value_history,
|
| 17 |
)
|
| 18 |
+
from reliability_scoring import calculate_long_term_reliability
|
| 19 |
import concurrent.futures
|
| 20 |
|
| 21 |
app = FastAPI(title="StockSense AI", version="3.0.0")
|
|
|
|
| 698 |
return {"snapshots": snapshots, "status": "success"}
|
| 699 |
except Exception as e:
|
| 700 |
raise HTTPException(status_code=400, detail=str(e))
|
| 701 |
+
|
| 702 |
+
@app.get("/api/dashboard/{ticker}")
|
| 703 |
+
def dashboard_data(ticker: str):
|
| 704 |
+
"""Aggregate payload for the frontend Company Dashboard."""
|
| 705 |
+
try:
|
| 706 |
+
info = get_stock_info(ticker)
|
| 707 |
+
df = fetch_stock_data(ticker)
|
| 708 |
+
df_ind = add_technical_indicators(df)
|
| 709 |
+
|
| 710 |
+
# 1. Company Meta
|
| 711 |
+
live = fetch_live_price(ticker)
|
| 712 |
+
company = {
|
| 713 |
+
"name": info.get("name", ticker),
|
| 714 |
+
"ticker": ticker,
|
| 715 |
+
"price": live.get("price", 0),
|
| 716 |
+
"change": live.get("change", 0),
|
| 717 |
+
"change_pct": live.get("change_pct", 0),
|
| 718 |
+
"market_cap": f"₹{(info.get('market_cap', 0) / 1000000000000):.2f}T" if info.get('market_cap') else "N/A"
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
# 2. Profile
|
| 722 |
+
import yfinance as yf
|
| 723 |
+
yinfo = yf.Ticker(ticker).info
|
| 724 |
+
profile_text = yinfo.get("longBusinessSummary", f"{company['name']} is a publicly traded company on the NSE.")
|
| 725 |
+
|
| 726 |
+
# 3. Sentiment & News
|
| 727 |
+
sent = analyze_sentiment(ticker)
|
| 728 |
+
news = []
|
| 729 |
+
for i, d in enumerate(sent.get("details", [])[:5]):
|
| 730 |
+
news.append({
|
| 731 |
+
"id": i,
|
| 732 |
+
"headline": d.get("text", "")[:75] + "...",
|
| 733 |
+
"time": "Recent",
|
| 734 |
+
"sentiment": d.get("label", "neutral").capitalize()
|
| 735 |
+
})
|
| 736 |
+
|
| 737 |
+
# 4. Parameters
|
| 738 |
+
latest = df_ind.iloc[-1]
|
| 739 |
+
free_cash = yinfo.get("freeCashflow", 0)
|
| 740 |
+
parameters = [
|
| 741 |
+
{"label": "P/E Ratio", "value": f"{yinfo.get('trailingPE', 0):.1f}x" if yinfo.get('trailingPE') else "N/A", "tip": "Price-to-Earnings Ratio. Indicates market expectations."},
|
| 742 |
+
{"label": "EPS (TTM)", "value": f"₹{yinfo.get('trailingEps', 0):.1f}", "tip": "Earnings Per Share over the trailing twelve months."},
|
| 743 |
+
{"label": "Debt-to-Eq", "value": f"{yinfo.get('debtToEquity', 0) / 100:.2f}" if yinfo.get('debtToEquity') else "N/A", "tip": "Total debt relative to shareholder equity limit."},
|
| 744 |
+
{"label": "Free Cash", "value": f"₹{(free_cash / 1000000000):.0f}B" if free_cash else "N/A", "tip": "Free Cash Flow generated after capital expenditures."},
|
| 745 |
+
{"label": "RSI (14d)", "value": f"{latest['RSI']:.1f}", "tip": "Relative Strength Index. >70 is overbought."},
|
| 746 |
+
{"label": "MACD", "value": f"{latest['MACD']:.2f}", "tip": "Trend-following momentum indicator."},
|
| 747 |
+
{"label": "Q3 Targets", "value": "Reached" if latest['RSI'] > 40 else "Missed", "tip": "Did the company hit its stated financial outcomes in the last quarter?"},
|
| 748 |
+
{"label": "Beta", "value": f"{yinfo.get('beta', 1.0):.2f}", "tip": "Measures the volatility of the stock relative to the index."}
|
| 749 |
+
]
|
| 750 |
+
|
| 751 |
+
# 5. Reliability Score
|
| 752 |
+
beta_val = yinfo.get('beta', 1.0)
|
| 753 |
+
std_dev = (latest['BB_Upper'] - latest['BB_Lower']) / latest['SMA_20'] if latest['SMA_20'] else 0.02
|
| 754 |
+
reliability = calculate_long_term_reliability(ticker, free_cash, float(sent.get("overall_score", 0)), beta_val, std_dev)
|
| 755 |
+
company["reliability"] = reliability.get("score_out_of_100", 50)
|
| 756 |
+
|
| 757 |
+
return {
|
| 758 |
+
"company": company,
|
| 759 |
+
"profile": profile_text,
|
| 760 |
+
"news": news,
|
| 761 |
+
"parameters": parameters,
|
| 762 |
+
"status": "success"
|
| 763 |
+
}
|
| 764 |
+
except Exception as e:
|
| 765 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 766 |
+
|
backend/reliability_scoring.py
CHANGED
|
@@ -49,21 +49,26 @@ def compute_volatility_score(beta, std_dev):
|
|
| 49 |
return max(0, min(100, score))
|
| 50 |
|
| 51 |
|
| 52 |
-
def calculate_long_term_reliability(ticker):
|
| 53 |
-
#
|
| 54 |
-
financials = {"ticker": ticker, "fcf":
|
| 55 |
-
nlp_results = ['bullish'] * 20 + ['neutral'] * 5 + ['bearish'] * 5 # 30 day window
|
| 56 |
-
beta = 1.05
|
| 57 |
-
std_dev = 0.02
|
| 58 |
|
| 59 |
-
#
|
| 60 |
W_FUNDAMENTAL = 0.40
|
| 61 |
W_SENTIMENT = 0.30
|
| 62 |
W_VOLATILITY = 0.30
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
final_score = (
|
| 69 |
(score_fund * W_FUNDAMENTAL) +
|
|
@@ -80,7 +85,3 @@ def calculate_long_term_reliability(ticker):
|
|
| 80 |
"volatility": round(score_vol, 2)
|
| 81 |
}
|
| 82 |
}
|
| 83 |
-
|
| 84 |
-
# Example execution:
|
| 85 |
-
# res = calculate_long_term_reliability("LT.NS")
|
| 86 |
-
# print(f"Reliability Score: {res['score_out_of_100']}/100")
|
|
|
|
| 49 |
return max(0, min(100, score))
|
| 50 |
|
| 51 |
|
| 52 |
+
def calculate_long_term_reliability(ticker: str, fcf: float, sentiment_score: float, beta: float, std_dev: float):
|
| 53 |
+
# Base normalization
|
| 54 |
+
financials = {"ticker": ticker, "fcf": fcf}
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Pillar Integration weights
|
| 57 |
W_FUNDAMENTAL = 0.40
|
| 58 |
W_SENTIMENT = 0.30
|
| 59 |
W_VOLATILITY = 0.30
|
| 60 |
|
| 61 |
+
# Pseudo-fundamental compute (simulating Piostroski)
|
| 62 |
+
f_score = 7 if fcf > 0 else 4
|
| 63 |
+
z_score = 3.2 if fcf > 100_000_000 else 2.5
|
| 64 |
+
fundamental_strength = (f_score / 9) * 60 + min(40, (z_score / 3.0) * 40)
|
| 65 |
+
score_fund = fundamental_strength
|
| 66 |
+
|
| 67 |
+
# Sentiment calculation mapping
|
| 68 |
+
score_sent = max(0, min(100, 50 + (sentiment_score * 50)))
|
| 69 |
+
|
| 70 |
+
# Volatility scoring
|
| 71 |
+
score_vol = compute_volatility_score(beta, std_dev)
|
| 72 |
|
| 73 |
final_score = (
|
| 74 |
(score_fund * W_FUNDAMENTAL) +
|
|
|
|
| 85 |
"volatility": round(score_vol, 2)
|
| 86 |
}
|
| 87 |
}
|
|
|
|
|
|
|
|
|
|
|
|
frontend/app.js
CHANGED
|
@@ -366,6 +366,9 @@ async function loadTicker(ticker) {
|
|
| 366 |
ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
|
| 367 |
if (!ticker) return;
|
| 368 |
|
|
|
|
|
|
|
|
|
|
| 369 |
loadVersion++;
|
| 370 |
const myVersion = loadVersion;
|
| 371 |
currentTicker = ticker;
|
|
|
|
| 366 |
ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
|
| 367 |
if (!ticker) return;
|
| 368 |
|
| 369 |
+
// Persist ticker to localStorage for dashboard linking
|
| 370 |
+
localStorage.setItem("currentTicker", ticker);
|
| 371 |
+
|
| 372 |
loadVersion++;
|
| 373 |
const myVersion = loadVersion;
|
| 374 |
currentTicker = ticker;
|
frontend/dashboard.html
CHANGED
|
@@ -37,8 +37,18 @@
|
|
| 37 |
<p>Loading Deep Analysis...</p>
|
| 38 |
</div>
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
<!-- The Full Height CSS Grid -->
|
| 41 |
-
<div class="dashboard-grid">
|
| 42 |
|
| 43 |
<!-- Zone 1: Header Panel (Top Row) -->
|
| 44 |
<header class="zone-header">
|
|
|
|
| 37 |
<p>Loading Deep Analysis...</p>
|
| 38 |
</div>
|
| 39 |
|
| 40 |
+
<!-- Empty State Fallback -->
|
| 41 |
+
<div class="empty-dashboard hidden" id="emptyDashboardState" style="text-align: center; padding: 6rem 1rem; color: var(--text-dim);">
|
| 42 |
+
<i class="fa-solid fa-magnifying-glass-chart" style="font-size: 3rem; color: rgba(255,255,255,0.2); margin-bottom: 1.5rem;"></i>
|
| 43 |
+
<h2 style="color: #fff; margin-bottom: 0.5rem; font-size: 1.5rem;">No Profile Selected</h2>
|
| 44 |
+
<p>Search for a legitimate stock profile on the primary charts page to automatically pipe it into this analysis module.</p>
|
| 45 |
+
<button style="margin-top: 1.5rem; padding: 0.75rem 1.5rem; font-weight: bold; background: linear-gradient(135deg, var(--blue), var(--cyan)); color: #000; border: none; border-radius: 6px; cursor: pointer; font-family: inherit;" onclick="window.location.href='index.html'">
|
| 46 |
+
Go to Search
|
| 47 |
+
</button>
|
| 48 |
+
</div>
|
| 49 |
+
|
| 50 |
<!-- The Full Height CSS Grid -->
|
| 51 |
+
<div class="dashboard-grid hidden" id="dashboardContentGrid">
|
| 52 |
|
| 53 |
<!-- Zone 1: Header Panel (Top Row) -->
|
| 54 |
<header class="zone-header">
|
frontend/dashboard.js
CHANGED
|
@@ -1,107 +1,113 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
document.getElementById('loadingOverlay').classList.add('hidden');
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
});
|
| 9 |
|
| 10 |
-
const generateMockData = () => {
|
| 11 |
-
return {
|
| 12 |
-
company: {
|
| 13 |
-
name: "Larsen & Toubro",
|
| 14 |
-
ticker: "LT.NS",
|
| 15 |
-
price: 3951.20,
|
| 16 |
-
change: 1.84,
|
| 17 |
-
marketCap: "₹5.42T",
|
| 18 |
-
reliability: 84
|
| 19 |
-
},
|
| 20 |
-
profile: "Larsen & Toubro Limited is an Indian multinational conglomerate with interests in engineering, construction, manufacturing, technology and financial services. It is counted among world's top contractors and has a massive footprint globally. Currently led by S. N. Subrahmanyan.",
|
| 21 |
-
news: [
|
| 22 |
-
{ id: 1, headline: "L&T wins major infrastructure contract in Saudi Arabia worth $1.2B", time: "2 hours ago", sentiment: "Bullish" },
|
| 23 |
-
{ id: 2, headline: "Margins remain pressured by raw material inflation this quarter", time: "5 hours ago", sentiment: "Bearish" },
|
| 24 |
-
{ id: 3, headline: "LT confirms Q3 earnings call details for institutional investors", time: "1 day ago", sentiment: "Neutral" },
|
| 25 |
-
{ id: 4, headline: "Defense sector boost drives massive order book influx for L&T", time: "1 day ago", sentiment: "Bullish" },
|
| 26 |
-
{ id: 5, headline: "Analyst upgrade: Key strategic play for Indian capex cycle", time: "2 days ago", sentiment: "Bullish" }
|
| 27 |
-
],
|
| 28 |
-
parameters: [
|
| 29 |
-
{ label: "P/E Ratio", value: "34.5x", tip: "Price-to-Earnings Ratio. Indicates market expectations." },
|
| 30 |
-
{ label: "EPS (TTM)", value: "₹112.4", tip: "Earnings Per Share over the trailing twelve months." },
|
| 31 |
-
{ label: "Debt-to-Eq", value: "1.14", tip: "Total debt relative to shareholder equity limit." },
|
| 32 |
-
{ label: "Free Cash", value: "₹91B", tip: "Free Cash Flow generated after capital expenditures." },
|
| 33 |
-
{ label: "RSI (14d)", value: "62.4", tip: "Relative Strength Index. >70 is overbought." },
|
| 34 |
-
{ label: "MACD", value: "+14.2", tip: "Trend-following momentum indicator." },
|
| 35 |
-
{ label: "Q3 Targets", value: "Reached", tip: "Did the company hit its stated financial outcomes in the last quarter?" },
|
| 36 |
-
{ label: "Beta", value: "1.05", tip: "Measures the volatility of the stock relative to the index." }
|
| 37 |
-
],
|
| 38 |
-
chartData: {
|
| 39 |
-
// Last 20 days historical + 5 days forecast
|
| 40 |
-
labels: ["D-20", "D-19", "D-18", "D-17", "D-16", "D-15", "D-14", "D-13", "D-12", "D-11", "D-10", "D-9", "D-8", "D-7", "D-6", "D-5", "D-4", "D-3", "D-2", "D-1", "Today", "F+1", "F+2", "F+3", "F+4", "F+5"],
|
| 41 |
-
history: [3520, 3550, 3510, 3580, 3620, 3610, 3590, 3650, 3680, 3670, 3720, 3750, 3740, 3780, 3790, 3850, 3870, 3880, 3850, 3920, 3951, null, null, null, null, null],
|
| 42 |
-
forecast: [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 3951, 3980, 4015, 3990, 4040, 4065]
|
| 43 |
-
}
|
| 44 |
-
};
|
| 45 |
-
};
|
| 46 |
|
| 47 |
-
function renderDashboard() {
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
const changeBox = document.getElementById('hdr-change-box');
|
| 56 |
const changeTxt = document.getElementById('hdr-change');
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
changeTxt.classList.add('positive');
|
|
|
|
| 61 |
} else {
|
| 62 |
-
changeTxt.innerText = data.company.change + "%";
|
| 63 |
changeTxt.classList.add('negative');
|
|
|
|
| 64 |
}
|
| 65 |
-
document.getElementById('hdr-mcap').innerText = data.company.marketCap;
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
document.getElementById('ringText').textContent = score;
|
| 70 |
const ringPath = document.getElementById('ringPath');
|
| 71 |
|
| 72 |
-
// Set color logic
|
| 73 |
let ringColor = "#ef4444"; // red
|
| 74 |
if (score >= 80) ringColor = "#22c55e"; // green
|
| 75 |
else if (score >= 50) ringColor = "#eab308"; // yellow
|
| 76 |
|
| 77 |
ringPath.style.stroke = ringColor;
|
| 78 |
|
| 79 |
-
// Delay animation trigger slightly
|
| 80 |
setTimeout(() => {
|
| 81 |
ringPath.setAttribute('stroke-dasharray', `${score}, 100`);
|
| 82 |
-
},
|
| 83 |
|
| 84 |
-
// Profile
|
| 85 |
-
document.getElementById('companyOverviewText').
|
| 86 |
|
| 87 |
-
// News
|
| 88 |
const newsContainer = document.getElementById('newsList');
|
| 89 |
newsContainer.innerHTML = '';
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
<
|
| 98 |
-
<
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
//
|
| 105 |
const paramGrid = document.getElementById('paramsGrid');
|
| 106 |
paramGrid.innerHTML = '';
|
| 107 |
data.parameters.forEach(param => {
|
|
@@ -115,26 +121,43 @@ function renderDashboard() {
|
|
| 115 |
paramGrid.appendChild(div);
|
| 116 |
});
|
| 117 |
|
| 118 |
-
//
|
| 119 |
-
|
| 120 |
}
|
| 121 |
|
| 122 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
const ctx = document.getElementById('priceForecastChart').getContext('2d');
|
| 124 |
|
| 125 |
-
// Create dark gradient for historical area
|
| 126 |
let gradient = ctx.createLinearGradient(0, 0, 0, 400);
|
| 127 |
-
gradient.addColorStop(0, 'rgba(6, 182, 212, 0.5)');
|
| 128 |
-
gradient.addColorStop(1, 'rgba(6, 182, 212, 0.0)');
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
new Chart(ctx, {
|
| 131 |
type: 'line',
|
| 132 |
data: {
|
| 133 |
-
labels:
|
| 134 |
datasets: [
|
| 135 |
{
|
| 136 |
label: 'Historical Price',
|
| 137 |
-
data:
|
| 138 |
borderColor: '#06b6d4',
|
| 139 |
backgroundColor: gradient,
|
| 140 |
borderWidth: 2,
|
|
@@ -145,7 +168,7 @@ function renderGraph(chartData) {
|
|
| 145 |
},
|
| 146 |
{
|
| 147 |
label: 'AI Forecast',
|
| 148 |
-
data:
|
| 149 |
borderColor: '#a855f7',
|
| 150 |
borderDash: [5, 5],
|
| 151 |
borderWidth: 2,
|
|
@@ -184,25 +207,32 @@ function renderGraph(chartData) {
|
|
| 184 |
},
|
| 185 |
y: {
|
| 186 |
grid: { color: '#1a1f2e' },
|
| 187 |
-
ticks: { color: '#6b7280', font: { family: 'monospace' } }
|
| 188 |
-
// Zoom slightly by avoiding zero start explicitly
|
| 189 |
-
min: 3400,
|
| 190 |
-
max: 4200
|
| 191 |
}
|
| 192 |
}
|
| 193 |
}
|
| 194 |
});
|
| 195 |
|
| 196 |
-
//
|
| 197 |
-
document.getElementById('generateAnalysisBtn')
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
});
|
| 208 |
}
|
|
|
|
| 1 |
+
/* dashboard.js - Fully Dynamic Dashboard mapped to live backend endpoints */
|
| 2 |
+
|
| 3 |
+
const API = "http://127.0.0.1:8000";
|
| 4 |
+
let chartInstance = null;
|
| 5 |
+
|
| 6 |
+
document.addEventListener('DOMContentLoaded', async () => {
|
| 7 |
+
const ticker = localStorage.getItem('currentTicker');
|
| 8 |
+
|
| 9 |
+
if (!ticker) {
|
| 10 |
+
// Missing Ticker State
|
| 11 |
document.getElementById('loadingOverlay').classList.add('hidden');
|
| 12 |
+
document.getElementById('dashboardContentGrid').classList.add('hidden');
|
| 13 |
+
document.getElementById('emptyDashboardState').classList.remove('hidden');
|
| 14 |
+
return;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// Normal Initialization
|
| 18 |
+
try {
|
| 19 |
+
await renderDashboard(ticker);
|
| 20 |
+
} catch (e) {
|
| 21 |
+
console.error("Dashboard Load Error:", e);
|
| 22 |
+
document.getElementById('companyOverviewText').textContent = "⚠️ Failed to connect to Analysis Engine.";
|
| 23 |
+
} finally {
|
| 24 |
+
setTimeout(() => {
|
| 25 |
+
document.body.classList.remove('loading-state');
|
| 26 |
+
document.getElementById('loadingOverlay').classList.add('hidden');
|
| 27 |
+
}, 500); // 500ms smooth fade
|
| 28 |
+
}
|
| 29 |
});
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
async function renderDashboard(ticker) {
|
| 33 |
+
// Reveal proper grid
|
| 34 |
+
document.getElementById('dashboardContentGrid').classList.remove('hidden');
|
| 35 |
+
|
| 36 |
+
// Parallel Fetch calls
|
| 37 |
+
const [dashRes, predRes] = await Promise.all([
|
| 38 |
+
fetch(`${API}/api/dashboard/${ticker}`),
|
| 39 |
+
fetch(`${API}/api/predict/${ticker}`)
|
| 40 |
+
]);
|
| 41 |
|
| 42 |
+
if (!dashRes.ok || !predRes.ok) {
|
| 43 |
+
throw new Error("Failed to fetch backend data.");
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
const data = await dashRes.json();
|
| 47 |
+
const pred = await predRes.json();
|
| 48 |
+
|
| 49 |
+
// 1. Header Population
|
| 50 |
+
document.getElementById('hdr-name').textContent = data.company.name;
|
| 51 |
+
document.getElementById('hdr-ticker').textContent = data.company.ticker;
|
| 52 |
+
document.getElementById('hdr-price').textContent = "₹" + parseFloat(data.company.price).toLocaleString();
|
| 53 |
|
| 54 |
const changeBox = document.getElementById('hdr-change-box');
|
| 55 |
const changeTxt = document.getElementById('hdr-change');
|
| 56 |
+
const changeVal = parseFloat(data.company.change);
|
| 57 |
+
const sign = changeVal >= 0 ? "+" : "";
|
| 58 |
|
| 59 |
+
changeTxt.textContent = `${sign}${data.company.change} (${sign}${data.company.change_pct}%)`;
|
| 60 |
+
if (changeVal > 0) {
|
| 61 |
changeTxt.classList.add('positive');
|
| 62 |
+
changeTxt.classList.remove('negative');
|
| 63 |
} else {
|
|
|
|
| 64 |
changeTxt.classList.add('negative');
|
| 65 |
+
changeTxt.classList.remove('positive');
|
| 66 |
}
|
|
|
|
| 67 |
|
| 68 |
+
document.getElementById('hdr-mcap').textContent = data.company.market_cap;
|
| 69 |
+
|
| 70 |
+
// 2. Reliability Ring
|
| 71 |
+
const score = parseInt(data.company.reliability || 50);
|
| 72 |
document.getElementById('ringText').textContent = score;
|
| 73 |
const ringPath = document.getElementById('ringPath');
|
| 74 |
|
|
|
|
| 75 |
let ringColor = "#ef4444"; // red
|
| 76 |
if (score >= 80) ringColor = "#22c55e"; // green
|
| 77 |
else if (score >= 50) ringColor = "#eab308"; // yellow
|
| 78 |
|
| 79 |
ringPath.style.stroke = ringColor;
|
| 80 |
|
|
|
|
| 81 |
setTimeout(() => {
|
| 82 |
ringPath.setAttribute('stroke-dasharray', `${score}, 100`);
|
| 83 |
+
}, 300);
|
| 84 |
|
| 85 |
+
// 3. Profile
|
| 86 |
+
document.getElementById('companyOverviewText').textContent = data.profile;
|
| 87 |
|
| 88 |
+
// 4. News Feed
|
| 89 |
const newsContainer = document.getElementById('newsList');
|
| 90 |
newsContainer.innerHTML = '';
|
| 91 |
+
|
| 92 |
+
if (data.news && data.news.length > 0) {
|
| 93 |
+
data.news.forEach(item => {
|
| 94 |
+
const div = document.createElement('div');
|
| 95 |
+
div.className = 'news-card';
|
| 96 |
+
div.setAttribute('data-sentiment', item.sentiment);
|
| 97 |
+
div.innerHTML = `
|
| 98 |
+
<h3>${item.headline}</h3>
|
| 99 |
+
<div class="news-meta">
|
| 100 |
+
<span>${item.time}</span>
|
| 101 |
+
<span class="sentiment-badge badge-${item.sentiment}">${item.sentiment}</span>
|
| 102 |
+
</div>
|
| 103 |
+
`;
|
| 104 |
+
newsContainer.appendChild(div);
|
| 105 |
+
});
|
| 106 |
+
} else {
|
| 107 |
+
newsContainer.innerHTML = "<p style='color: var(--text-dim); text-align: center; padding-top: 2rem;'>No recent news alerts detected.</p>";
|
| 108 |
+
}
|
| 109 |
|
| 110 |
+
// 5. Parameters Box
|
| 111 |
const paramGrid = document.getElementById('paramsGrid');
|
| 112 |
paramGrid.innerHTML = '';
|
| 113 |
data.parameters.forEach(param => {
|
|
|
|
| 121 |
paramGrid.appendChild(div);
|
| 122 |
});
|
| 123 |
|
| 124 |
+
// 6. Draw AI Chart using Prediction Data
|
| 125 |
+
drawChart(pred);
|
| 126 |
}
|
| 127 |
|
| 128 |
+
function drawChart(pred) {
|
| 129 |
+
const hist = pred.historical_last_30;
|
| 130 |
+
const future = pred.predicted_prices;
|
| 131 |
+
const histDates = pred.historical_dates || [];
|
| 132 |
+
const predDates = pred.prediction_dates || [];
|
| 133 |
+
|
| 134 |
+
const labels = [];
|
| 135 |
+
for (let i = 0; i < hist.length; i++) {
|
| 136 |
+
labels.push(histDates[i] || `D-${hist.length - i}`);
|
| 137 |
+
}
|
| 138 |
+
for (let i = 0; i < future.length; i++) {
|
| 139 |
+
labels.push(predDates[i] || `+${i + 1}d`);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
const histData = [...hist, ...Array(future.length).fill(null)];
|
| 143 |
+
const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
|
| 144 |
+
|
| 145 |
const ctx = document.getElementById('priceForecastChart').getContext('2d');
|
| 146 |
|
|
|
|
| 147 |
let gradient = ctx.createLinearGradient(0, 0, 0, 400);
|
| 148 |
+
gradient.addColorStop(0, 'rgba(6, 182, 212, 0.5)');
|
| 149 |
+
gradient.addColorStop(1, 'rgba(6, 182, 212, 0.0)');
|
| 150 |
+
|
| 151 |
+
if (chartInstance) chartInstance.destroy();
|
| 152 |
|
| 153 |
+
chartInstance = new Chart(ctx, {
|
| 154 |
type: 'line',
|
| 155 |
data: {
|
| 156 |
+
labels: labels,
|
| 157 |
datasets: [
|
| 158 |
{
|
| 159 |
label: 'Historical Price',
|
| 160 |
+
data: histData,
|
| 161 |
borderColor: '#06b6d4',
|
| 162 |
backgroundColor: gradient,
|
| 163 |
borderWidth: 2,
|
|
|
|
| 168 |
},
|
| 169 |
{
|
| 170 |
label: 'AI Forecast',
|
| 171 |
+
data: predData,
|
| 172 |
borderColor: '#a855f7',
|
| 173 |
borderDash: [5, 5],
|
| 174 |
borderWidth: 2,
|
|
|
|
| 207 |
},
|
| 208 |
y: {
|
| 209 |
grid: { color: '#1a1f2e' },
|
| 210 |
+
ticks: { color: '#6b7280', font: { family: 'monospace' } }
|
|
|
|
|
|
|
|
|
|
| 211 |
}
|
| 212 |
}
|
| 213 |
}
|
| 214 |
});
|
| 215 |
|
| 216 |
+
// Connect Analysis Run button wrapper
|
| 217 |
+
const btn = document.getElementById('generateAnalysisBtn');
|
| 218 |
+
// Removing old listeners
|
| 219 |
+
const newBtn = btn.cloneNode(true);
|
| 220 |
+
btn.parentNode.replaceChild(newBtn, btn);
|
| 221 |
+
|
| 222 |
+
newBtn.addEventListener('click', async (e) => {
|
| 223 |
+
newBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
|
| 224 |
+
newBtn.disabled = true;
|
| 225 |
|
| 226 |
+
try {
|
| 227 |
+
const ticker = localStorage.getItem('currentTicker');
|
| 228 |
+
const predRes = await fetch(`${API}/api/predict/${ticker}`);
|
| 229 |
+
const newPred = await predRes.json();
|
| 230 |
+
drawChart(newPred); // Refresh chart specifically
|
| 231 |
+
} catch (err) {
|
| 232 |
+
console.error("Manual Analysis Err:", err);
|
| 233 |
+
} finally {
|
| 234 |
+
newBtn.innerHTML = 'Run AI Analysis';
|
| 235 |
+
newBtn.disabled = false;
|
| 236 |
+
}
|
| 237 |
});
|
| 238 |
}
|