Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

feat: add EquityValuationTab with DCF, Altman Z, Piotroski F, Beneish M scoring

somya254987ed8da4ea537
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index bb8a4b04d..ca62d5882 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1777,6 +1777,8 @@ set(SCREEN_SOURCES
src/screens/equity_research/EquityFinancialsTab_Views.cpp
src/screens/equity_research/EquityFinancialsTab_Populate.cpp
src/screens/equity_research/EquityAnalysisTab.cpp
+ src/screens/equity_research/EquityValuationTab.h
+ src/screens/equity_research/EquityValuationTab.cpp
src/screens/equity_research/EquityTechnicalsTab.cpp
src/screens/equity_research/EquityTalippTab.cpp
src/screens/equity_research/EquityPeersTab.cpp
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 37bc9831d..5859ba2ef 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -1,4 +1,11 @@
// src/screens/equity_research/EquityResearchScreen.cpp
+
+// ═══════════════════════════════════════════════════════════════════════════════
+// INCLUDES
+// These are like "import" statements. They tell the compiler which other files
+// this file needs to use. Without these, the compiler doesn't know what
+// QWidget, QLabel, etc. are.
+// ═══════════════════════════════════════════════════════════════════════════════
#include "screens/equity_research/EquityResearchScreen.h"
#include "core/events/EventBus.h"
@@ -17,6 +24,8 @@
#include "screens/equity_research/EquitySentimentTab.h"
#include "screens/equity_research/EquityTalippTab.h"
#include "screens/equity_research/EquityTechnicalsTab.h"
+
+#include "screens/equity_research/EquityValuationTab.h"
#include "services/backtesting/BacktestingService.h"
#include "services/equity/EquityResearchService.h"
#include "ui/theme/Theme.h"
@@ -42,44 +51,68 @@
#include <QTimeZone>
#include <QVBoxLayout>
+// ═══════════════════════════════════════════════════════════════════════════════
+// NAMESPACE
+// "namespace fincept::screens" is like a folder/package for the code.
+// All the code below belongs to that namespace so names don't clash with
+// other parts of the app that might use the same class names.
+// ═══════════════════════════════════════════════════════════════════════════════
namespace fincept::screens {
+// ═══════════════════════════════════════════════════════════════════════════════
+// CONSTRUCTOR
+// This runs once when EquityResearchScreen is first created.
+// Think of it as the "setup" function for the whole screen.
+// ═══════════════════════════════════════════════════════════════════════════════
EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
- build_ui();
- retranslateUi();
+ build_ui(); // Step 1: build all the visual widgets
+ retranslateUi(); // Step 2: set all the text labels (supports multiple languages)
- // Refresh timer — only started in showEvent
+ // A timer that refreshes the stock quote every 30 seconds automatically.
+ // It only starts when the screen is visible (see showEvent below).
refresh_timer_ = new QTimer(this);
- refresh_timer_->setInterval(30 * 1000); // 30s quote refresh
+ refresh_timer_->setInterval(30 * 1000); // 30,000 milliseconds = 30 seconds
connect(refresh_timer_, &QTimer::timeout, this, [this]() {
if (!current_symbol_.isEmpty())
services::equity::EquityResearchService::instance().load_symbol(current_symbol_);
});
- // Wire service signals
+ // "connect" wires signals to slots.
+ // When the service finishes loading a quote or stock info,
+ // it emits a signal → our slot functions get called automatically.
auto& svc = services::equity::EquityResearchService::instance();
- connect(&svc, &services::equity::EquityResearchService::quote_loaded, this, &EquityResearchScreen::on_quote_loaded);
- connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityResearchScreen::on_info_loaded);
-
- // Listen for navigation from CommandBar asset search
+ connect(&svc, &services::equity::EquityResearchService::quote_loaded,
+ this, &EquityResearchScreen::on_quote_loaded);
+ connect(&svc, &services::equity::EquityResearchService::info_loaded,
+ this, &EquityResearchScreen::on_info_loaded);
+ connect(&svc, &services::equity::EquityResearchService::financials_loaded,
+ this, &EquityResearchScreen::on_financials_loaded);
+
+ // Listen on the app-wide event bus for "load this symbol" requests
+ // from other parts of the app (e.g. the command bar search).
EventBus::instance().subscribe("equity_research.load_symbol", [this](const QVariantMap& payload) {
const QString symbol = payload.value("symbol").toString();
if (!symbol.isEmpty())
load_symbol(symbol);
});
- // Default symbol
+ // Load Apple as the default stock when the screen first opens.
load_symbol("AAPL");
- // Drop any dragged symbol onto the screen to jump the research view
- // to that ticker. Uses the existing load_symbol path so caching,
- // signals, and the EventBus publish stay consistent.
+ // Allow dragging a symbol from another panel and dropping it here
+ // to switch the research view to that stock.
symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
if (ref.is_valid())
load_symbol(ref.symbol);
});
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// showEvent / hideEvent
+// Qt calls these automatically when the screen becomes visible or hidden.
+// We use them to start/stop the refresh timer so we don't waste API calls
+// when the user isn't even looking at this screen.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
refresh_timer_->start();
@@ -92,20 +125,32 @@ void EquityResearchScreen::hideEvent(QHideEvent* e) {
refresh_timer_->stop();
}
-// ── UI construction ───────────────────────────────────────────────────────────
+// ═══════════════════════════════════════════════════════════════════════════════
+// build_ui()
+// Creates every visual element on screen:
+// - the top title bar
+// - the quote bar (price, change, volume)
+// - the tab widget with all the sub-tabs
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::build_ui() {
- setStyleSheet(QString("background:%1; color:%2;").arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
+ // Set dark background and primary text color for the whole screen
+ setStyleSheet(QString("background:%1; color:%2;")
+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
+ // QVBoxLayout stacks children vertically (top to bottom)
auto* vl = new QVBoxLayout(this);
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
- vl->addWidget(build_title_bar());
- vl->addWidget(build_quote_bar());
+ vl->addWidget(build_title_bar()); // row 1: "EQUITY RESEARCH AAPL [BACKTEST] [CSV]"
+ vl->addWidget(build_quote_bar()); // row 2: price, change %, volume, H/L, mkt cap
- // ── Tabs ─────────────────────────────────────────────────────────────────
+ // ── Tab Widget ───────────────────────────────────────────────────────────
+ // QTabWidget is the clickable tabs bar + the content area below it.
tab_widget_ = new QTabWidget;
- tab_widget_->setDocumentMode(true);
+ tab_widget_->setDocumentMode(true); // cleaner look, no border around pane
+
+ // Style the tab bar using Qt StyleSheets (similar to CSS)
tab_widget_->setStyleSheet(QString(R"(
QTabWidget::pane { border:0; background:%1; }
QTabBar::tab {
@@ -114,62 +159,80 @@ void EquityResearchScreen::build_ui() {
font-size:12px; text-transform:uppercase; letter-spacing:1px;
}
QTabBar::tab:selected { color:%4; border-bottom:2px solid %4; }
- QTabBar::tab:hover { color:%5; }
+ QTabBar::tab:hover { color:%5; }
)")
- .arg(ui::colors::BG_BASE(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(),
- ui::colors::AMBER(), ui::colors::TEXT_PRIMARY()));
+ .arg(ui::colors::BG_BASE(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(),
+ ui::colors::AMBER(), ui::colors::TEXT_PRIMARY()));
- overview_tab_ = new EquityOverviewTab;
+ // Create one instance of each tab widget.
+ // Each tab is its own class that knows how to display its own content.
+ overview_tab_ = new EquityOverviewTab;
financials_tab_ = new EquityFinancialsTab;
- analysis_tab_ = new EquityAnalysisTab;
+ analysis_tab_ = new EquityAnalysisTab;
technicals_tab_ = new EquityTechnicalsTab;
- talipp_tab_ = new EquityTalippTab;
- peers_tab_ = new EquityPeersTab;
- news_tab_ = new EquityNewsTab;
- sentiment_tab_ = new EquitySentimentTab;
-
- // Tab titles are re-set by retranslateUi(); add with placeholder strings
- // first so the tab order remains fixed regardless of locale text width.
- tab_widget_->addTab(overview_tab_, QString());
- tab_widget_->addTab(financials_tab_, QString());
- tab_widget_->addTab(analysis_tab_, QString());
- tab_widget_->addTab(technicals_tab_, QString());
- tab_widget_->addTab(talipp_tab_, QString());
- tab_widget_->addTab(peers_tab_, QString());
- tab_widget_->addTab(news_tab_, QString());
- tab_widget_->addTab(sentiment_tab_, QString());
-
- connect(tab_widget_, &QTabWidget::currentChanged, this, &EquityResearchScreen::on_tab_changed);
-
- vl->addWidget(tab_widget_, 1);
+ talipp_tab_ = new EquityTalippTab;
+ peers_tab_ = new EquityPeersTab;
+ news_tab_ = new EquityNewsTab;
+ sentiment_tab_ = new EquitySentimentTab;
+ valuation_tab_ = new EquityValuationTab; // ← our new tab
+
+ // addTab(widget, label) registers each tab.
+ // We pass empty QString() as label because retranslateUi() sets
+ // the real text — this way tab ORDER never depends on text width.
+ tab_widget_->addTab(overview_tab_, QString()); // index 0
+ tab_widget_->addTab(financials_tab_, QString()); // index 1
+ tab_widget_->addTab(analysis_tab_, QString()); // index 2
+ tab_widget_->addTab(technicals_tab_, QString()); // index 3
+ tab_widget_->addTab(talipp_tab_, QString()); // index 4
+ tab_widget_->addTab(peers_tab_, QString()); // index 5
+ tab_widget_->addTab(news_tab_, QString()); // index 6
+ tab_widget_->addTab(sentiment_tab_, QString()); // index 7
+ tab_widget_->addTab(valuation_tab_, QString()); // index 8 ← new
+
+ // When the user clicks a different tab, call on_tab_changed()
+ connect(tab_widget_, &QTabWidget::currentChanged,
+ this, &EquityResearchScreen::on_tab_changed);
+
+ vl->addWidget(tab_widget_, 1); // "1" = stretch factor, fills remaining height
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// build_title_bar()
+// Builds the top bar: "EQUITY RESEARCH AAPL [BACKTEST] [↓ CSV]"
+// Returns a QWidget* that build_ui() adds to the layout.
+// ═══════════════════════════════════════════════════════════════════════════════
QWidget* EquityResearchScreen::build_title_bar() {
auto* container = new QWidget(this);
container->setFixedHeight(48);
container->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ // QHBoxLayout stacks children horizontally (left to right)
auto* hl = new QHBoxLayout(container);
hl->setContentsMargins(16, 8, 16, 8);
hl->setSpacing(12);
+ // "EQUITY RESEARCH" text on the left
title_label_ = new QLabel;
title_label_->setStyleSheet(
- QString("color:%1; font-size:14px; font-weight:700; letter-spacing:2px;").arg(ui::colors::AMBER()));
+ QString("color:%1; font-size:14px; font-weight:700; letter-spacing:2px;")
+ .arg(ui::colors::AMBER()));
hl->addWidget(title_label_);
+ // Current symbol (e.g. "AAPL") — draggable to other panels
symbol_label_ = new QLabel;
- symbol_label_->setStyleSheet(QString("color:%1; font-size:14px; font-weight:600;").arg(ui::colors::TEXT_PRIMARY()));
+ symbol_label_->setStyleSheet(
+ QString("color:%1; font-size:14px; font-weight:600;")
+ .arg(ui::colors::TEXT_PRIMARY()));
symbol_label_->setCursor(Qt::OpenHandCursor);
- // Drag-out: pull the current symbol from the live member so the filter
- // always ships the most recent ticker, not whatever was loaded at build.
symbol_dnd::installDragSource(
symbol_label_,
[this]() { return current_symbol(); },
link_group_);
hl->addWidget(symbol_label_);
+ // BACKTEST button — sends user to the backtesting screen with this symbol
auto* backtest_btn = new QPushButton(tr("BACKTEST"), container);
backtest_btn->setCursor(Qt::PointingHandCursor);
backtest_btn->setFixedHeight(24);
@@ -177,27 +240,24 @@ QWidget* EquityResearchScreen::build_title_bar() {
QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"
"padding:0 10px; font-size:%3px; font-family:%4; font-weight:700; letter-spacing:0.5px; }"
"QPushButton:hover { background:%5; color:%6; }")
- .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM())
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
connect(backtest_btn, &QPushButton::clicked, this, [this]() {
if (current_symbol_.isEmpty()) return;
QJsonObject config;
QJsonArray symbols;
symbols.append(current_symbol_);
config["symbols"] = symbols;
- // Run a basic backtest of this symbol automatically on arrival
- // (default provider/command/strategy + preconfigured settings).
config["autoRun"] = true;
services::backtest::BacktestingService::instance().set_pending_portfolio_config(config);
- // exclusive=true → replace the current view with the Backtesting screen
- // instead of auto-tiling it into a split grid slot alongside this one.
EventBus::instance().publish("nav.switch_screen",
- {{"screen_id", QString("backtesting")}, {"exclusive", true}});
+ {{"screen_id", QString("backtesting")}, {"exclusive", true}});
});
hl->addWidget(backtest_btn);
+ // CSV download button — opens a dialog to download price history
auto* csv_btn = new QPushButton(tr("↓ CSV"), container);
csv_btn->setCursor(Qt::PointingHandCursor);
csv_btn->setFixedHeight(24);
@@ -206,32 +266,39 @@ QWidget* EquityResearchScreen::build_title_bar() {
QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"
"padding:0 10px; font-size:%3px; font-family:%4; font-weight:700; letter-spacing:0.5px; }"
"QPushButton:hover { background:%5; color:%6; }")
- .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM())
- .arg(ui::fonts::TINY)
- .arg(ui::fonts::DATA_FAMILY)
- .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
connect(csv_btn, &QPushButton::clicked, this, &EquityResearchScreen::on_download_csv_clicked);
hl->addWidget(csv_btn);
- hl->addStretch();
+ hl->addStretch(); // pushes the hint label to the far right
hint_label_ = new QLabel;
- hint_label_->setStyleSheet(QString("color:%1; font-size:12px;").arg(ui::colors::TEXT_TERTIARY()));
+ hint_label_->setStyleSheet(
+ QString("color:%1; font-size:12px;").arg(ui::colors::TEXT_TERTIARY()));
hl->addWidget(hint_label_);
return container;
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// build_quote_bar()
+// The second bar showing: price, % change, volume, H/L, market cap
+// ═══════════════════════════════════════════════════════════════════════════════
QWidget* EquityResearchScreen::build_quote_bar() {
auto* bar = new QFrame;
bar->setFixedHeight(44);
bar->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(16, 0, 16, 0);
hl->setSpacing(24);
+ // Lambda helper to create a styled label and add it to the layout
auto make_label = [&](const QString& txt, const QString& color = "") -> QLabel* {
auto* l = new QLabel(txt);
QString style = "font-size:13px; font-weight:600;";
@@ -244,45 +311,60 @@ QWidget* EquityResearchScreen::build_quote_bar() {
return l;
};
- // Em-dash placeholders are typographic, not text — left raw. The VOL/H/L/
- // MKT CAP prefixes are translated via retranslateUi().
- sym_label_ = make_label(QStringLiteral("—"), ui::colors::AMBER());
- price_label_ = make_label(QStringLiteral("—"), ui::colors::TEXT_PRIMARY());
+ // Each make_label call creates one piece of the quote bar and saves
+ // the pointer so we can update the text later when data arrives.
+ sym_label_ = make_label(QStringLiteral("—"), ui::colors::AMBER());
+ price_label_ = make_label(QStringLiteral("—"), ui::colors::TEXT_PRIMARY());
change_label_ = make_label(QStringLiteral("—"));
- vol_label_ = make_label(QString());
- hl_label_ = make_label(QString());
+ vol_label_ = make_label(QString());
+ hl_label_ = make_label(QString());
mktcap_label_ = make_label(QString());
- rec_label_ = make_label(QStringLiteral("—"));
+ rec_label_ = make_label(QStringLiteral("—"));
hl->addStretch();
return bar;
}
-// ── Slots ─────────────────────────────────────────────────────────────────────
+// ═══════════════════════════════════════════════════════════════════════════════
+// SLOTS
+// Slots are functions that get called automatically when a signal fires.
+// ═══════════════════════════════════════════════════════════════════════════════
+
+// Called when a new quote (price/change/volume) arrives from the service
void EquityResearchScreen::on_quote_loaded(services::equity::QuoteData q) {
update_quote_bar(q);
}
+// Called when full stock info (company details, market cap, etc.) arrives
void EquityResearchScreen::on_info_loaded(services::equity::StockInfo info) {
+ // Guard: ignore data for a different symbol (can happen if user switches fast)
if (info.symbol != current_symbol_)
return;
current_currency_ = info.currency;
- // Populate the title-bar MKT CAP. The value comes straight from yfinance's
- // `info` (the Overview tab renders the same StockInfo::market_cap); the title
- // bar simply was never wired to it, so it sat at the "—" placeholder.
+ // Update the market cap label in the title bar
if (mktcap_label_) {
if (info.market_cap > 0) {
- const QString cs =
- EquityOverviewTab::currency_symbol(info.currency.isEmpty() ? "USD" : info.currency);
+ const QString cs = EquityOverviewTab::currency_symbol(
+ info.currency.isEmpty() ? "USD" : info.currency);
mktcap_label_->setText(
tr("MKT CAP: %1%2").arg(cs, EquityOverviewTab::fmt_large(info.market_cap)));
} else {
mktcap_label_->setText(tr("MKT CAP: %1").arg(QStringLiteral("—")));
}
}
+ if (valuation_tab_)
+ valuation_tab_->set_stock_info(info);
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// on_tab_changed(int index)
+// Called every time the user clicks a different tab.
+// "index" is which tab they clicked (0=Overview, 1=Financials, etc.)
+//
+// This is "lazy loading" — we only fetch data for a tab when the user
+// actually opens it, instead of loading everything upfront.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::on_tab_changed(int index) {
ScreenStateManager::instance().notify_changed(this);
if (current_symbol_.isEmpty())
@@ -290,6 +372,7 @@ void EquityResearchScreen::on_tab_changed(int index) {
auto& svc = services::equity::EquityResearchService::instance();
+
switch (index) {
case 1:
financials_tab_->set_symbol(current_symbol_);
@@ -297,7 +380,6 @@ void EquityResearchScreen::on_tab_changed(int index) {
break;
case 2:
analysis_tab_->set_symbol(current_symbol_);
- // Re-trigger load_symbol — cache will re-emit info_loaded immediately
svc.load_symbol(current_symbol_);
break;
case 3:
@@ -317,44 +399,56 @@ void EquityResearchScreen::on_tab_changed(int index) {
case 7:
sentiment_tab_->set_symbol(current_symbol_);
break;
- default:
+ case 8:
+ // FIX 3: "set_symbol" not "set symbol" (no space!)
+ valuation_tab_->set_symbol(current_symbol_);
+ // Also fetch financial data needed for scoring models
+ svc.fetch_financials(current_symbol_);
break;
+ default:
+ break; // case 0 (Overview) needs no lazy load
}
}
-// ── Helpers ───────────────────────────────────────────────────────────────────
+// ═══════════════════════════════════════════════════════════════════════════════
+// load_symbol(symbol)
+// The main entry point when the user wants to research a different stock.
+// Called from: command bar, drag-and-drop, EventBus, restore_state().
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::load_symbol(const QString& symbol) {
+ // Don't reload if it's already the current symbol
if (symbol.isEmpty() || symbol == current_symbol_)
return;
current_symbol_ = symbol;
- // Update title bar and quote bar
+ // Update the text in title bar and quote bar immediately
symbol_label_->setText(symbol);
sym_label_->setText(symbol);
price_label_->setText(tr("Loading…"));
- // Overview always loads (tab 0 is default)
+ // Overview tab always refreshes (it's the default landing tab)
overview_tab_->set_symbol(symbol);
- // Load data for currently active tab
+ // Also refresh whichever tab is currently open
on_tab_changed(tab_widget_->currentIndex());
- // Trigger quote + info + historical
+ // Tell the service to go fetch quote + info data from the API
services::equity::EquityResearchService::instance().load_symbol(symbol);
- // Subscribe to broker live quote if this is an Indian stock with Fyers connected
if (isVisible())
hub_subscribe_broker_quote();
- // Publish to linked group so Watchlist/EquityTrading/News/etc. follow.
+ // Broadcast the new symbol to other linked panels (watchlist, trading, etc.)
if (link_group_ != SymbolGroup::None) {
SymbolContext::instance().set_group_symbol(
link_group_, SymbolRef::equity(symbol), this);
}
}
-// ── IGroupLinked ─────────────────────────────────────────────────────────────
-
+// ═══════════════════════════════════════════════════════════════════════════════
+// IGroupLinked — when another panel in the same link group changes symbol,
+// this screen follows automatically.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::on_group_symbol_changed(const SymbolRef& ref) {
if (ref.is_valid())
load_symbol(ref.symbol);
@@ -366,44 +460,51 @@ SymbolRef EquityResearchScreen::current_symbol() const {
return SymbolRef::equity(current_symbol_);
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// update_quote_bar(q)
+// Fills in the live price data row from a QuoteData object.
+// Called by on_quote_loaded() and hub_subscribe_broker_quote() callback.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::update_quote_bar(const services::equity::QuoteData& q) {
if (q.symbol != current_symbol_)
return;
- const QString cs = EquityOverviewTab::currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_);
+ const QString cs = EquityOverviewTab::currency_symbol(
+ current_currency_.isEmpty() ? "USD" : current_currency_);
sym_label_->setText(q.symbol);
price_label_->setText(QString("%1%2").arg(cs).arg(q.price, 0, 'f', 2));
bool up = q.change_pct >= 0;
- QString arrow = up ? "\xe2\x96\xb2" : "\xe2\x96\xbc";
+ QString arrow = up ? "\xe2\x96\xb2" : "\xe2\x96\xbc"; // ▲ or ▼
QString chg_color = up ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();
change_label_->setText(QString("%1%2 %3%4%")
- .arg(up ? "+" : "")
- .arg(q.change, 0, 'f', 2)
- .arg(arrow)
- .arg(qAbs(q.change_pct), 0, 'f', 2));
- change_label_->setStyleSheet(QString("font-size:13px; font-weight:600; color:%1;").arg(chg_color));
-
+ .arg(up ? "+" : "")
+ .arg(q.change, 0, 'f', 2)
+ .arg(arrow)
+ .arg(qAbs(q.change_pct), 0, 'f', 2));
+ change_label_->setStyleSheet(
+ QString("font-size:13px; font-weight:600; color:%1;").arg(chg_color));
+
+ // Format volume: show 1.2B, 450M, 12K instead of raw numbers
auto fmt_vol = [](double v) -> QString {
- if (v >= 1e9)
- return QString("%1B").arg(v / 1e9, 0, 'f', 1);
- if (v >= 1e6)
- return QString("%1M").arg(v / 1e6, 0, 'f', 1);
- if (v >= 1e3)
- return QString("%1K").arg(v / 1e3, 0, 'f', 0);
+ if (v >= 1e9) return QString("%1B").arg(v / 1e9, 0, 'f', 1);
+ if (v >= 1e6) return QString("%1M").arg(v / 1e6, 0, 'f', 1);
+ if (v >= 1e3) return QString("%1K").arg(v / 1e3, 0, 'f', 0);
return QString::number(static_cast<qint64>(v));
};
vol_label_->setText(tr("VOL: %1").arg(fmt_vol(q.volume)));
- hl_label_->setText(tr("H:%1%2 L:%1%3").arg(cs).arg(q.high, 0, 'f', 2).arg(q.low, 0, 'f', 2));
+ hl_label_->setText(tr("H:%1%2 L:%1%3")
+ .arg(cs).arg(q.high, 0, 'f', 2).arg(q.low, 0, 'f', 2));
}
-// ── CSV price-data download (yfinance) ───────────────────────────────────────
-// current_symbol_ is already in yfinance form on this screen (the quote/info/
-// historical loads all pass it straight through), so it is handed to
-// historical_period unchanged — no exchange-suffix resolution needed here.
-
+// ═══════════════════════════════════════════════════════════════════════════════
+// on_download_csv_clicked()
+// Opens a dialog to let the user choose period/interval, then downloads
+// OHLCV price data from Yahoo Finance and saves it as a CSV file.
+// Uses PythonRunner to call yfinance in the background (async).
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::on_download_csv_clicked() {
const QString symbol = current_symbol_.trimmed();
if (symbol.isEmpty()) {
@@ -440,8 +541,7 @@ void EquityResearchScreen::on_download_csv_clicked() {
root->addLayout(form);
auto* note = new QLabel(
- tr("Note: intraday intervals (below 1d) are only available for roughly the last 60 days."),
- dlg);
+ tr("Note: intraday intervals (below 1d) are only available for roughly the last 60 days."), dlg);
note->setWordWrap(true);
note->setStyleSheet(QString("color:%1; font-size:10px;").arg(ui::colors::TEXT_TERTIARY()));
root->addWidget(note);
@@ -453,7 +553,7 @@ void EquityResearchScreen::on_download_csv_clicked() {
auto* buttons = new QHBoxLayout();
buttons->addStretch();
- auto* cancel_btn = new QPushButton(tr("Cancel"), dlg);
+ auto* cancel_btn = new QPushButton(tr("Cancel"), dlg);
auto* download_btn = new QPushButton(tr("Download"), dlg);
download_btn->setDefault(true);
buttons->addWidget(cancel_btn);
@@ -463,98 +563,95 @@ void EquityResearchScreen::on_download_csv_clicked() {
connect(cancel_btn, &QPushButton::clicked, dlg, &QDialog::reject);
connect(download_btn, &QPushButton::clicked, dlg,
- [dlg, symbol, period_combo, interval_combo, status, download_btn, cancel_btn]() {
- const QString period = period_combo->currentText();
- const QString interval = interval_combo->currentText();
-
- auto set_busy = [=](bool busy) {
- download_btn->setEnabled(!busy);
- cancel_btn->setEnabled(!busy);
- period_combo->setEnabled(!busy);
- interval_combo->setEnabled(!busy);
- };
- set_busy(true);
- status->setVisible(true);
- status->setStyleSheet(
- QString("color:%1; font-size:11px;").arg(ui::colors::TEXT_SECONDARY()));
- status->setText(tr("Fetching from Yahoo Finance…"));
-
- // Terminal step: write the OHLCV array to a user-chosen CSV file.
- auto finish = [=](const QJsonArray& candles) {
- if (candles.isEmpty()) {
- status->setStyleSheet(
- QString("color:%1; font-size:11px;").arg(ui::colors::NEGATIVE()));
- status->setText(tr("No data returned for %1 (%2). Try a longer period "
- "or a daily interval.")
- .arg(symbol, interval));
- set_busy(false);
- return;
- }
-
- QString safe;
- for (const QChar ch : symbol)
- safe += ch.isLetterOrNumber() ? ch : QChar('_');
- const QString suggested =
- QStringLiteral("%1_%2_%3.csv").arg(safe, period, interval);
- const QString path = QFileDialog::getSaveFileName(
- dlg, tr("Save Price Data"), suggested, tr("CSV Files (*.csv)"));
- if (path.isEmpty()) {
- status->setText(tr("Save cancelled."));
- set_busy(false);
- return;
- }
-
- QFile file(path);
- if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
- QMessageBox::warning(
- dlg, tr("Export failed"),
- tr("Could not open the file for writing:\n%1").arg(file.errorString()));
- set_busy(false);
- return;
- }
- QTextStream out(&file);
- out.setEncoding(QStringConverter::Utf8);
- out << "datetime,timestamp,open,high,low,close,volume\n";
- for (const auto& v : candles) {
- const QJsonObject c = v.toObject();
- const auto ts = static_cast<qint64>(c.value("timestamp").toDouble());
- const QString dt = QDateTime::fromSecsSinceEpoch(ts, QTimeZone::UTC)
- .toString("yyyy-MM-dd HH:mm:ss");
- out << dt << ',' << ts << ',' << c.value("open").toDouble() << ','
- << c.value("high").toDouble() << ',' << c.value("low").toDouble() << ','
- << c.value("close").toDouble() << ','
- << static_cast<qint64>(c.value("volume").toDouble()) << '\n';
- }
- file.close();
- QMessageBox::information(
- dlg, tr("Download complete"),
- tr("Saved %1 rows for %2 to:\n%3").arg(candles.size()).arg(symbol, path));
- dlg->accept();
- };
-
- // historical_period is daemon-routed in PythonRunner, so this is fast.
- QPointer<QDialog> guard(dlg);
- python::PythonRunner::instance().run(
- "yfinance_data.py", {"historical_period", symbol, period, interval},
- [guard, finish](python::PythonResult res) {
- if (!guard)
- return;
- finish(QJsonDocument::fromJson(python::extract_json(res.output).toUtf8())
- .array());
- });
- });
+ [dlg, symbol, period_combo, interval_combo, status, download_btn, cancel_btn]() {
+ const QString period = period_combo->currentText();
+ const QString interval = interval_combo->currentText();
+
+ auto set_busy = [=](bool busy) {
+ download_btn->setEnabled(!busy);
+ cancel_btn->setEnabled(!busy);
+ period_combo->setEnabled(!busy);
+ interval_combo->setEnabled(!busy);
+ };
+ set_busy(true);
+ status->setVisible(true);
+ status->setStyleSheet(
+ QString("color:%1; font-size:11px;").arg(ui::colors::TEXT_SECONDARY()));
+ status->setText(tr("Fetching from Yahoo Finance…"));
+
+ auto finish = [=](const QJsonArray& candles) {
+ if (candles.isEmpty()) {
+ status->setStyleSheet(
+ QString("color:%1; font-size:11px;").arg(ui::colors::NEGATIVE()));
+ status->setText(tr("No data returned for %1 (%2). Try a longer period or a daily interval.")
+ .arg(symbol, interval));
+ set_busy(false);
+ return;
+ }
+
+ QString safe;
+ for (const QChar ch : symbol)
+ safe += ch.isLetterOrNumber() ? ch : QChar('_');
+ const QString suggested =
+ QStringLiteral("%1_%2_%3.csv").arg(safe, period, interval);
+ const QString path = QFileDialog::getSaveFileName(
+ dlg, tr("Save Price Data"), suggested, tr("CSV Files (*.csv)"));
+ if (path.isEmpty()) {
+ status->setText(tr("Save cancelled."));
+ set_busy(false);
+ return;
+ }
+
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
+ QMessageBox::warning(dlg, tr("Export failed"),
+ tr("Could not open the file for writing:\n%1").arg(file.errorString()));
+ set_busy(false);
+ return;
+ }
+ QTextStream out(&file);
+ out.setEncoding(QStringConverter::Utf8);
+ out << "datetime,timestamp,open,high,low,close,volume\n";
+ for (const auto& v : candles) {
+ const QJsonObject c = v.toObject();
+ const auto ts = static_cast<qint64>(c.value("timestamp").toDouble());
+ const QString dt = QDateTime::fromSecsSinceEpoch(ts, QTimeZone::UTC)
+ .toString("yyyy-MM-dd HH:mm:ss");
+ out << dt << ',' << ts << ','
+ << c.value("open").toDouble() << ','
+ << c.value("high").toDouble() << ','
+ << c.value("low").toDouble() << ','
+ << c.value("close").toDouble() << ','
+ << static_cast<qint64>(c.value("volume").toDouble()) << '\n';
+ }
+ file.close();
+ QMessageBox::information(dlg, tr("Download complete"),
+ tr("Saved %1 rows for %2 to:\n%3").arg(candles.size()).arg(symbol, path));
+ dlg->accept();
+ };
+
+ // QPointer guard: if the dialog is closed before the Python call
+ // returns, "guard" becomes null and the callback safely does nothing.
+ QPointer<QDialog> guard(dlg);
+ python::PythonRunner::instance().run(
+ "yfinance_data.py", {"historical_period", symbol, period, interval},
+ [guard, finish](python::PythonResult res) {
+ if (!guard) return;
+ finish(QJsonDocument::fromJson(
+ python::extract_json(res.output).toUtf8()).array());
+ });
+ });
dlg->exec();
dlg->deleteLater();
}
-// ── Re-translation ───────────────────────────────────────────────────────────
-// The quote bar is mostly numeric data — only the label prefixes (VOL/H/L,
-// MKT CAP) need localization. update_quote_bar() rewrites VOL/H/L on every
-// quote refresh, so when the language changes the next refresh will pick up
-// the new prefix automatically. MKT CAP shows "MKT CAP: —" until populated;
-// retranslate handles the placeholder.
-
+// ═══════════════════════════════════════════════════════════════════════════════
+// changeEvent / retranslateUi
+// Qt calls changeEvent when the app language changes.
+// retranslateUi() re-sets all user-visible text to the new language.
+// tr("...") marks a string as translatable.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi();
@@ -576,16 +673,24 @@ void EquityResearchScreen::retranslateUi() {
tab_widget_->setTabText(1, tr("Financials"));
tab_widget_->setTabText(2, tr("Analysis"));
tab_widget_->setTabText(3, tr("Technicals"));
- // "TALIpp" is a library name — kept verbatim across locales.
- tab_widget_->setTabText(4, QStringLiteral("TALIpp"));
+ tab_widget_->setTabText(4, QStringLiteral("TALIpp")); // library name, not translated
tab_widget_->setTabText(5, tr("Peers"));
tab_widget_->setTabText(6, tr("News"));
tab_widget_->setTabText(7, tr("Sentiment"));
+ tab_widget_->setTabText(8, tr("Valuation")); // ← our new tab label
}
}
+// ═══════════════════════════════════════════════════════════════════════════════
+// save_state / restore_state
+// Used by the screen manager to remember which symbol and tab were open
+// when the user closes and reopens the panel.
+// ═══════════════════════════════════════════════════════════════════════════════
QVariantMap EquityResearchScreen::save_state() const {
- QVariantMap state{{"symbol", current_symbol_}, {"tab_index", tab_widget_ ? tab_widget_->currentIndex() : 0}};
+ QVariantMap state{
+ {"symbol", current_symbol_},
+ {"tab_index", tab_widget_ ? tab_widget_->currentIndex() : 0}
+ };
if (peers_tab_) state["peers"] = peers_tab_->peers_text();
return state;
}
@@ -605,62 +710,64 @@ void EquityResearchScreen::restore_state(const QVariantMap& state) {
peers_tab_->set_peers_text(state.value("peers").toString());
}
-// ── Broker live quote subscription ──────────────────────────────────────────
-
+// ═══════════════════════════════════════════════════════════════════════════════
+// Broker live quote subscription (Fyers integration)
+// For Indian stocks (.NS/.BO), if Fyers is connected, we subscribe to a
+// real-time data stream instead of the 30s polling timer.
+// ═══════════════════════════════════════════════════════════════════════════════
void EquityResearchScreen::hub_subscribe_broker_quote() {
hub_unsubscribe_broker_quote();
- if (current_symbol_.isEmpty())
- return;
- // Only Indian stocks are streamable via Fyers
- if (!current_symbol_.endsWith(QStringLiteral(".NS")) && !current_symbol_.endsWith(QStringLiteral(".BO")))
+ if (current_symbol_.isEmpty()) return;
+ if (!current_symbol_.endsWith(QStringLiteral(".NS")) &&
+ !current_symbol_.endsWith(QStringLiteral(".BO")))
return;
- // Find a connected Fyers account
const auto accounts = trading::AccountManager::instance().active_accounts();
QString fyers_account_id;
for (const auto& a : accounts) {
- if (a.broker_id == QStringLiteral("fyers") && a.state == trading::ConnectionState::Connected) {
+ if (a.broker_id == QStringLiteral("fyers") &&
+ a.state == trading::ConnectionState::Connected) {
fyers_account_id = a.account_id;
break;
}
}
- if (fyers_account_id.isEmpty())
- return;
+ if (fyers_account_id.isEmpty()) return;
- // Strip .NS/.BO suffix to get plain broker symbol
QString broker_sym = current_symbol_.left(current_symbol_.length() - 3);
- const QString topic = trading::broker_topic(QStringLiteral("fyers"), fyers_account_id,
- QStringLiteral("quote"), broker_sym);
+ const QString topic = trading::broker_topic(
+ QStringLiteral("fyers"), fyers_account_id, QStringLiteral("quote"), broker_sym);
const QString sym = current_symbol_;
datahub::DataHub::instance().subscribe(this, topic, [this, sym](const QVariant& v) {
- if (!v.canConvert<trading::BrokerQuote>())
- return;
+ if (!v.canConvert<trading::BrokerQuote>()) return;
const auto bq = v.value<trading::BrokerQuote>();
services::equity::QuoteData qd;
- qd.symbol = sym;
- qd.price = bq.ltp;
- qd.change = bq.change;
+ qd.symbol = sym;
+ qd.price = bq.ltp;
+ qd.change = bq.change;
qd.change_pct = bq.change_pct;
- qd.high = bq.high;
- qd.low = bq.low;
- qd.volume = bq.volume;
- qd.timestamp = bq.timestamp;
+ qd.high = bq.high;
+ qd.low = bq.low;
+ qd.volume = bq.volume;
+ qd.timestamp = bq.timestamp;
update_quote_bar(qd);
});
- refresh_timer_->stop(); // broker stream is faster than 30s polling
+ refresh_timer_->stop(); // broker stream replaces polling
hub_broker_active_ = true;
}
void EquityResearchScreen::hub_unsubscribe_broker_quote() {
- if (!hub_broker_active_)
- return;
+ if (!hub_broker_active_) return;
datahub::DataHub::instance().unsubscribe(this);
hub_broker_active_ = false;
if (isVisible())
refresh_timer_->start();
}
+void EquityResearchScreen::on_financials_loaded(services::equity::FinancialsData data) {
+ if (valuation_tab_)
+ valuation_tab_->set_financials(data);
+}
-} // namespace fincept::screens
+} // namespace fincept::screens
\ No newline at end of file
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index d92a50cb0..a741201c0 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -1,4 +1,3 @@
-// src/screens/equity_research/EquityResearchScreen.h
#pragma once
#include "core/symbol/IGroupLinked.h"
#include "screens/common/IStatefulScreen.h"
@@ -21,6 +20,7 @@ class EquityTalippTab;
class EquityPeersTab;
class EquityNewsTab;
class EquitySentimentTab;
+class EquityValuationTab;
class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGroupLinked {
Q_OBJECT
@@ -32,9 +32,6 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
QVariantMap save_state() const override;
QString state_key() const override { return "equity_research"; }
- // IGroupLinked — receives group broadcasts and calls load_symbol();
- // also publishes when load_symbol() is triggered internally via the
- // existing EventBus wiring (see .cpp).
void set_group(SymbolGroup g) override { link_group_ = g; }
SymbolGroup group() const override { return link_group_; }
void on_group_symbol_changed(const SymbolRef& ref) override;
@@ -49,9 +46,8 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void on_quote_loaded(services::equity::QuoteData quote);
void on_info_loaded(services::equity::StockInfo info);
void on_tab_changed(int index);
- // Opens the "Download Price Data (CSV)" dialog and exports yfinance OHLCV
- // history for current_symbol_ to a user-chosen file.
void on_download_csv_clicked();
+ void on_financials_loaded(services::equity::FinancialsData data);
private:
void build_ui();
@@ -63,38 +59,34 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void hub_subscribe_broker_quote();
void hub_unsubscribe_broker_quote();
- // Title bar
- QLabel* title_label_ = nullptr;
+ QLabel* title_label_ = nullptr;
QLabel* symbol_label_ = nullptr;
- QLabel* hint_label_ = nullptr;
+ QLabel* hint_label_ = nullptr;
- // Quote bar
- QLabel* sym_label_ = nullptr;
- QLabel* price_label_ = nullptr;
+ QLabel* sym_label_ = nullptr;
+ QLabel* price_label_ = nullptr;
QLabel* change_label_ = nullptr;
- QLabel* vol_label_ = nullptr;
- QLabel* hl_label_ = nullptr;
+ QLabel* vol_label_ = nullptr;
+ QLabel* hl_label_ = nullptr;
QLabel* mktcap_label_ = nullptr;
- QLabel* rec_label_ = nullptr;
+ QLabel* rec_label_ = nullptr;
- // Tabs
- QTabWidget* tab_widget_ = nullptr;
- EquityOverviewTab* overview_tab_ = nullptr;
+ QTabWidget* tab_widget_ = nullptr;
+ EquityOverviewTab* overview_tab_ = nullptr;
EquityFinancialsTab* financials_tab_ = nullptr;
- EquityAnalysisTab* analysis_tab_ = nullptr;
+ EquityAnalysisTab* analysis_tab_ = nullptr;
EquityTechnicalsTab* technicals_tab_ = nullptr;
- EquityTalippTab* talipp_tab_ = nullptr;
- EquityPeersTab* peers_tab_ = nullptr;
- EquityNewsTab* news_tab_ = nullptr;
- EquitySentimentTab* sentiment_tab_ = nullptr;
+ EquityTalippTab* talipp_tab_ = nullptr;
+ EquityPeersTab* peers_tab_ = nullptr;
+ EquityNewsTab* news_tab_ = nullptr;
+ EquitySentimentTab* sentiment_tab_ = nullptr;
+ EquityValuationTab* valuation_tab_ = nullptr;
- QTimer* refresh_timer_ = nullptr;
- QString current_symbol_;
- QString current_currency_;
- bool hub_broker_active_ = false;
-
- // Symbol group link — SymbolGroup::None when unlinked.
+ QTimer* refresh_timer_ = nullptr;
+ QString current_symbol_;
+ QString current_currency_;
+ bool hub_broker_active_ = false;
SymbolGroup link_group_ = SymbolGroup::None;
};
-} // namespace fincept::screens
+} // namespace fincept::screens
\ No newline at end of file
diff --git a/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp b/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp
new file mode 100644
index 000000000..cc0be9b8c
--- /dev/null
+++ b/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp
@@ -0,0 +1,684 @@
+// src/screens/equity_research/EquityValuationTab.cpp
+#include "screens/equity_research/EquityValuationTab.h"
+#include "services/quantlib/QuantLibClient.h"
+#include "ui/theme/Theme.h"
+
+#include <QEvent>
+#include <QFrame>
+#include <QGroupBox>
+#include <QHBoxLayout>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QLabel>
+#include <QScrollArea>
+#include <QVBoxLayout>
+
+namespace fincept::screens {
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Construction
+// ─────────────────────────────────────────────────────────────────────────────
+
+EquityValuationTab::EquityValuationTab(QWidget* parent)
+ : QWidget(parent)
+{
+ build_ui();
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// build_ui
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::build_ui() {
+ setStyleSheet(QString("background:%1; color:%2;")
+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ auto* scroll = new QScrollArea(this);
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroll->setStyleSheet("background:transparent; border:0;");
+
+ auto* content = new QWidget;
+ content->setStyleSheet("background:transparent;");
+ auto* vbox = new QVBoxLayout(content);
+ vbox->setContentsMargins(12, 12, 12, 12);
+ vbox->setSpacing(12);
+
+ build_dcf_section(vbox);
+ build_scoring_section(vbox);
+ build_multiples_section(vbox);
+ vbox->addStretch();
+
+ scroll->setWidget(content);
+ root->addWidget(scroll);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Section builders
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::build_dcf_section(QVBoxLayout* parent) {
+ auto* box = new QGroupBox(tr("DCF MODEL"));
+ box->setStyleSheet(QString(
+ "QGroupBox { border:1px solid %1; border-radius:4px; margin-top:8px;"
+ " font-size:11px; font-weight:700; color:%2; letter-spacing:1px; padding:8px; }"
+ "QGroupBox::title { subcontrol-origin:margin; left:8px; }")
+ .arg(ui::colors::BORDER_DIM(), ui::colors::AMBER()));
+
+ auto* hl = new QHBoxLayout(box);
+ hl->setSpacing(20);
+
+ // ── Left: inputs ──────────────────────────────────────────────
+ auto* left = new QWidget;
+ auto* form = new QVBoxLayout(left);
+ form->setSpacing(6);
+ form->setContentsMargins(0, 0, 0, 0);
+
+ auto make_spin = [&](const char* label_key, double min, double max,
+ double def, const QString& suffix, int dec) -> QDoubleSpinBox* {
+ auto* row = new QWidget;
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(8);
+
+ auto* lbl = new QLabel(tr(label_key));
+ lbl->setStyleSheet(QString("color:%1; font-size:11px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ lbl->setFixedWidth(130);
+ i18n_labels_[lbl] = label_key;
+
+ auto* spin = new QDoubleSpinBox;
+ spin->setRange(min, max);
+ spin->setValue(def);
+ spin->setSuffix(suffix);
+ spin->setDecimals(dec);
+ spin->setFixedWidth(120);
+ spin->setStyleSheet(QString(
+ "QDoubleSpinBox { background:%1; color:%2; border:1px solid %3;"
+ " padding:2px 4px; font-size:12px; }"
+ "QDoubleSpinBox::up-button, QDoubleSpinBox::down-button { width:16px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM()));
+
+ rl->addWidget(lbl);
+ rl->addWidget(spin);
+ rl->addStretch();
+ form->addWidget(row);
+ return spin;
+ };
+
+ fcf_input_ = make_spin("FREE CASH FLOW", -999999, 999999, 0.0, " M", 2);
+ growth_input_ = make_spin("GROWTH RATE", -50, 100, 8.0, " %", 2);
+ terminal_input_ = make_spin("TERMINAL GROWTH", 0, 10, 2.5, " %", 2);
+ discount_input_ = make_spin("DISCOUNT RATE", 1, 30, 10.0, " %", 2);
+ years_input_ = make_spin("PROJECTION YEARS", 5, 20, 10.0, " yrs", 0);
+ shares_input_ = make_spin("SHARES O/S", 0.01, 999999, 1.0, " M", 2);
+
+ calc_btn_ = new QPushButton(tr("CALCULATE"));
+ calc_btn_->setCursor(Qt::PointingHandCursor);
+ calc_btn_->setFixedHeight(28);
+ calc_btn_->setStyleSheet(QString(
+ "QPushButton { background:%1; color:%2; border:0; font-size:12px;"
+ " font-weight:700; letter-spacing:1px; border-radius:3px; }"
+ "QPushButton:hover { background:%3; }"
+ "QPushButton:disabled { background:%4; color:%5; }")
+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(),
+ ui::colors::AMBER_DIM(), ui::colors::BG_SURFACE(),
+ ui::colors::TEXT_TERTIARY()));
+ connect(calc_btn_, &QPushButton::clicked, this, &EquityValuationTab::on_calculate_clicked);
+ form->addWidget(calc_btn_);
+ form->addStretch();
+ hl->addWidget(left);
+
+ // ── Right: results ────────────────────────────────────────────
+ auto* right = new QWidget;
+ auto* rl2 = new QVBoxLayout(right);
+ rl2->setSpacing(8);
+ rl2->setContentsMargins(0, 0, 0, 0);
+
+ auto make_result_row = [&](const char* label_key, QLabel*& val_out,
+ const QString& val_color = "") {
+ auto* row = new QWidget;
+ auto* h = new QHBoxLayout(row);
+ h->setContentsMargins(0, 0, 0, 0);
+ h->setSpacing(8);
+
+ auto* lbl = new QLabel(tr(label_key));
+ lbl->setStyleSheet(QString("color:%1; font-size:11px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ lbl->setFixedWidth(130);
+ i18n_labels_[lbl] = label_key;
+
+ val_out = new QLabel(QStringLiteral("—"));
+ QString col = val_color.isEmpty() ? QString(ui::colors::TEXT_PRIMARY()) : val_color;
+ val_out->setStyleSheet(QString("color:%1; font-size:14px; font-weight:700;").arg(col));
+
+ h->addWidget(lbl);
+ h->addWidget(val_out);
+ h->addStretch();
+ rl2->addWidget(row);
+ };
+
+ make_result_row("INTRINSIC VALUE", intrinsic_val_, ui::colors::TEXT_PRIMARY());
+ make_result_row("CURRENT PRICE", current_price_val_, ui::colors::TEXT_SECONDARY());
+ make_result_row("MARGIN OF SAFETY", margin_val_, ui::colors::TEXT_PRIMARY());
+
+ verdict_badge_ = new QLabel;
+ verdict_badge_->setAlignment(Qt::AlignCenter);
+ verdict_badge_->setFixedHeight(24);
+ verdict_badge_->setStyleSheet("font-size:11px; font-weight:700;");
+ rl2->addWidget(verdict_badge_);
+ rl2->addStretch();
+
+ hl->addWidget(right);
+ parent->addWidget(box);
+}
+
+void EquityValuationTab::build_scoring_section(QVBoxLayout* parent) {
+ auto* box = new QGroupBox(tr("CREDIT QUALITY"));
+ box->setStyleSheet(QString(
+ "QGroupBox { border:1px solid %1; border-radius:4px; margin-top:8px;"
+ " font-size:11px; font-weight:700; color:%2; letter-spacing:1px; padding:8px; }"
+ "QGroupBox::title { subcontrol-origin:margin; left:8px; }")
+ .arg(ui::colors::BORDER_DIM(), ui::colors::AMBER()));
+
+ auto* vl = new QVBoxLayout(box);
+ vl->setSpacing(8);
+
+ scoring_note_ = new QLabel(tr("Open FINANCIALS tab first to enable scoring."));
+ scoring_note_->setStyleSheet(QString("color:%1; font-size:11px; font-style:italic;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ vl->addWidget(scoring_note_);
+
+ auto make_score_row = [&](const char* label_key, QLabel*& val_out, QLabel*& badge_out) {
+ auto* row = new QWidget;
+ auto* h = new QHBoxLayout(row);
+ h->setContentsMargins(0, 0, 0, 0);
+ h->setSpacing(12);
+
+ auto* lbl = new QLabel(tr(label_key));
+ lbl->setStyleSheet(QString("color:%1; font-size:12px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ lbl->setFixedWidth(140);
+ i18n_labels_[lbl] = label_key;
+
+ val_out = new QLabel(QStringLiteral("—"));
+ val_out->setStyleSheet(QString("color:%1; font-size:13px; font-weight:600;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ val_out->setFixedWidth(60);
+
+ badge_out = new QLabel;
+ badge_out->setAlignment(Qt::AlignCenter);
+ badge_out->setFixedHeight(20);
+ badge_out->setMinimumWidth(160);
+ badge_out->setStyleSheet("font-size:10px; font-weight:700;");
+
+ h->addWidget(lbl);
+ h->addWidget(val_out);
+ h->addWidget(badge_out);
+ h->addStretch();
+ vl->addWidget(row);
+ };
+
+ make_score_row("ALTMAN Z-SCORE", altman_val_, altman_badge_);
+ make_score_row("PIOTROSKI F", piotroski_val_, piotroski_badge_);
+ make_score_row("BENEISH M-SCORE", beneish_val_, beneish_badge_);
+
+ parent->addWidget(box);
+}
+
+void EquityValuationTab::build_multiples_section(QVBoxLayout* parent) {
+ auto* box = new QGroupBox(tr("ADVANCED MULTIPLES"));
+ box->setStyleSheet(QString(
+ "QGroupBox { border:1px solid %1; border-radius:4px; margin-top:8px;"
+ " font-size:11px; font-weight:700; color:%2; letter-spacing:1px; padding:8px; }"
+ "QGroupBox::title { subcontrol-origin:margin; left:8px; }")
+ .arg(ui::colors::BORDER_DIM(), ui::colors::AMBER()));
+
+ auto* grid = new QWidget;
+ auto* gl = new QHBoxLayout(grid);
+ gl->setSpacing(32);
+ gl->setContentsMargins(0, 0, 0, 0);
+
+ auto* col1 = new QVBoxLayout;
+ auto* col2 = new QVBoxLayout;
+
+ auto make_mult = [&](const char* label_key, QLabel*& val_out, QVBoxLayout* col) {
+ auto* row = new QWidget;
+ auto* h = new QHBoxLayout(row);
+ h->setContentsMargins(0, 0, 0, 0);
+ h->setSpacing(8);
+
+ auto* lbl = new QLabel(tr(label_key));
+ lbl->setStyleSheet(QString("color:%1; font-size:11px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ lbl->setFixedWidth(100);
+ i18n_labels_[lbl] = label_key;
+
+ val_out = new QLabel(QStringLiteral("—"));
+ val_out->setStyleSheet(QString("color:%1; font-size:13px; font-weight:600;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+
+ h->addWidget(lbl);
+ h->addWidget(val_out);
+ h->addStretch();
+ col->addWidget(row);
+ };
+
+ make_mult("EV/EBITDA", ev_ebitda_val_, col1);
+ make_mult("EV/REVENUE", ev_revenue_val_, col1);
+ make_mult("P/SALES", price_sales_val_, col2);
+ make_mult("GRAHAM NUMBER", graham_val_, col2);
+
+ gl->addLayout(col1);
+ gl->addLayout(col2);
+ gl->addStretch();
+
+ auto* vl = new QVBoxLayout(box);
+ vl->addWidget(grid);
+
+ parent->addWidget(box);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Public setters
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::set_symbol(const QString& symbol) {
+ if (symbol == current_symbol_) return;
+ current_symbol_ = symbol;
+ financials_loaded_ = false;
+ clear_results();
+ if (scoring_note_)
+ scoring_note_->setVisible(true);
+}
+
+void EquityValuationTab::set_stock_info(const services::equity::StockInfo& info) {
+ last_info_ = info;
+ current_price_ = info.current_price;
+ current_currency_ = info.currency;
+ pre_fill_dcf_inputs();
+
+ // Show current price in results panel immediately
+ if (current_price_val_)
+ current_price_val_->setText(fmt_currency(current_price_));
+}
+
+void EquityValuationTab::set_financials(const services::equity::FinancialsData& data) {
+ last_financials_ = data;
+ financials_loaded_ = true;
+ if (scoring_note_)
+ scoring_note_->setVisible(false);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Pre-fill DCF from StockInfo
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::pre_fill_dcf_inputs() {
+ if (!fcf_input_) return;
+
+ double fcf_m = last_info_.free_cashflow / 1e6;
+ double growth = last_info_.earnings_growth * 100.0;
+ double shares_m = last_info_.shares_outstanding / 1e6;
+ double wacc = 4.5 + last_info_.beta * 5.5; // CAPM approx
+
+ if (std::isfinite(fcf_m))
+ fcf_input_->setValue(fcf_m);
+ if (std::isfinite(growth) && growth > -100.0 && growth < 200.0)
+ growth_input_->setValue(growth);
+ if (std::isfinite(shares_m) && shares_m > 0.0)
+ shares_input_->setValue(shares_m);
+ if (std::isfinite(wacc) && wacc > 1.0 && wacc < 30.0)
+ discount_input_->setValue(wacc);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// CALCULATE slot
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::on_calculate_clicked() {
+ if (current_symbol_.isEmpty()) return;
+
+ // Validation: discount > terminal
+ if (discount_input_->value() <= terminal_input_->value()) {
+ if (margin_val_)
+ margin_val_->setText(tr("ERR: discount ≤ terminal"));
+ return;
+ }
+
+ calc_btn_->setEnabled(false);
+ calc_btn_->setText(tr("CALCULATING…"));
+
+ // ── 1. DCF ────────────────────────────────────────────────────
+ QJsonObject dcf_body;
+ dcf_body["free_cash_flow"] = fcf_input_->value() * 1e6;
+ dcf_body["growth_rate"] = growth_input_->value() / 100.0;
+ dcf_body["terminal_growth_rate"] = terminal_input_->value() / 100.0;
+ dcf_body["discount_rate"] = discount_input_->value() / 100.0;
+ dcf_body["projection_years"] = static_cast<int>(years_input_->value());
+ dcf_body["shares_outstanding"] = shares_input_->value() * 1e6;
+
+ QPointer<EquityValuationTab> self = this;
+ services::QuantLibClient::instance().call(
+ "analysis/valuation/dcf/fcff", dcf_body,
+ [self](mcp::ToolResult result) {
+ if (!self) return;
+ self->calc_btn_->setEnabled(true);
+ self->calc_btn_->setText(tr("CALCULATE"));
+ if (!result.success) {
+ if (self->intrinsic_val_)
+ self->intrinsic_val_->setText(tr("API error"));
+ return;
+ }
+ self->display_dcf_result(result.data);
+ });
+
+ // ── 2. Scoring (only if financials loaded) ─────────────────────
+ if (financials_loaded_)
+ run_scoring_models();
+
+ // ── 3. Multiples ──────────────────────────────────────────────
+ run_multiples();
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Scoring models
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::run_scoring_models() {
+ const auto& bs = last_financials_.balance_sheet;
+ const auto& is = last_financials_.income_statement;
+ const auto& cf = last_financials_.cash_flow;
+
+ double total_assets = get_stmt_val(bs, "Total Assets");
+ double total_liabilities = get_stmt_val(bs, "Total Liabilities Net Minority Interest");
+ double current_assets = get_stmt_val(bs, "Current Assets");
+ double current_liab = get_stmt_val(bs, "Current Liabilities");
+ double retained_earnings = get_stmt_val(bs, "Retained Earnings");
+ double revenue = get_stmt_val(is, "Total Revenue");
+ double ebit = get_stmt_val(is, "EBIT");
+ if (ebit == 0.0) ebit = get_stmt_val(is, "Operating Income");
+ double working_capital = (current_assets != 0.0 && current_liab != 0.0)
+ ? current_assets - current_liab
+ : get_stmt_val(bs, "Working Capital");
+
+ // ── Altman Z ─────────────────────────────────────────────────
+ QJsonObject altman_body;
+ altman_body["working_capital"] = working_capital;
+ altman_body["total_assets"] = total_assets;
+ altman_body["retained_earnings"] = retained_earnings;
+ altman_body["ebit"] = ebit;
+ altman_body["market_cap"] = last_info_.market_cap;
+ altman_body["total_liabilities"] = total_liabilities;
+ altman_body["revenue"] = revenue;
+
+ QPointer<EquityValuationTab> self = this;
+ services::QuantLibClient::instance().call(
+ "analysis/valuation/predictive/altman-z", altman_body,
+ [self](mcp::ToolResult r) {
+ if (!self || !r.success) return;
+ self->display_altman_result(r.data);
+ });
+
+ // ── Piotroski F (needs two periods) ──────────────────────────
+ if (is.size() >= 2 && bs.size() >= 2) {
+ QJsonObject pio_body;
+ // Period 0 = most recent, period 1 = prior year
+ pio_body["net_income"] = get_stmt_val(is, "Net Income");
+ pio_body["total_assets"] = get_stmt_val(bs, "Total Assets");
+ pio_body["operating_cashflow"] = get_stmt_val(cf, "Operating Cash Flow");
+ pio_body["long_term_debt"] = get_stmt_val(bs, "Long Term Debt");
+ pio_body["current_ratio"] = (current_liab > 0)
+ ? current_assets / current_liab : 0.0;
+ pio_body["shares_outstanding"] = last_info_.shares_outstanding;
+ pio_body["gross_profit"] = get_stmt_val(is, "Gross Profit");
+ pio_body["revenue"] = get_stmt_val(is, "Total Revenue");
+ // Prior year
+ pio_body["prev_total_assets"] = get_stmt_val(bs, "Total Assets", 1);
+ pio_body["prev_long_term_debt"] = get_stmt_val(bs, "Long Term Debt", 1);
+ pio_body["prev_current_assets"] = get_stmt_val(bs, "Current Assets", 1);
+ pio_body["prev_current_liabilities"]= get_stmt_val(bs, "Current Liabilities", 1);
+ pio_body["prev_shares_outstanding"] = last_info_.shares_outstanding;
+ pio_body["prev_gross_profit"] = get_stmt_val(is, "Gross Profit", 1);
+ pio_body["prev_revenue"] = get_stmt_val(is, "Total Revenue", 1);
+
+ services::QuantLibClient::instance().call(
+ "analysis/valuation/predictive/piotroski-f", pio_body,
+ [self](mcp::ToolResult r) {
+ if (!self || !r.success) return;
+ self->display_piotroski_result(r.data);
+ });
+ }
+
+ // ── Beneish M ────────────────────────────────────────────────
+ if (is.size() >= 2 && bs.size() >= 2) {
+ QJsonObject ben_body;
+ ben_body["revenue"] = get_stmt_val(is, "Total Revenue");
+ ben_body["prev_revenue"] = get_stmt_val(is, "Total Revenue", 1);
+ ben_body["receivables"] = get_stmt_val(bs, "Receivables");
+ ben_body["prev_receivables"] = get_stmt_val(bs, "Receivables", 1);
+ ben_body["gross_profit"] = get_stmt_val(is, "Gross Profit");
+ ben_body["prev_gross_profit"] = get_stmt_val(is, "Gross Profit", 1);
+ ben_body["total_assets"] = get_stmt_val(bs, "Total Assets");
+ ben_body["prev_total_assets"] = get_stmt_val(bs, "Total Assets", 1);
+ ben_body["long_term_debt"] = get_stmt_val(bs, "Long Term Debt");
+ ben_body["prev_long_term_debt"] = get_stmt_val(bs, "Long Term Debt", 1);
+ ben_body["current_assets"] = get_stmt_val(bs, "Current Assets");
+ ben_body["prev_current_assets"] = get_stmt_val(bs, "Current Assets", 1);
+ ben_body["ppe"] = get_stmt_val(bs, "Net PPE");
+ ben_body["prev_ppe"] = get_stmt_val(bs, "Net PPE", 1);
+ ben_body["net_income"] = get_stmt_val(is, "Net Income");
+ ben_body["prev_net_income"] = get_stmt_val(is, "Net Income", 1);
+ ben_body["operating_cashflow"] = get_stmt_val(cf, "Operating Cash Flow");
+
+ services::QuantLibClient::instance().call(
+ "analysis/valuation/predictive/beneish-m", ben_body,
+ [self](mcp::ToolResult r) {
+ if (!self || !r.success) return;
+ self->display_beneish_result(r.data);
+ });
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Multiples
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::run_multiples() {
+ // Use already-available StockInfo fields — no extra API call needed
+ // for EV/EBITDA, EV/Revenue, P/S. Graham Number needs EPS + book value.
+
+ if (ev_ebitda_val_)
+ ev_ebitda_val_->setText(last_info_.ev_to_ebitda > 0
+ ? QString("%1x").arg(last_info_.ev_to_ebitda, 0, 'f', 1)
+ : QStringLiteral("—"));
+
+ if (ev_revenue_val_)
+ ev_revenue_val_->setText(last_info_.ev_to_revenue > 0
+ ? QString("%1x").arg(last_info_.ev_to_revenue, 0, 'f', 1)
+ : QStringLiteral("—"));
+
+ if (price_sales_val_) {
+ double ps = (last_info_.total_revenue > 0 && last_info_.market_cap > 0)
+ ? last_info_.market_cap / last_info_.total_revenue
+ : 0.0;
+ price_sales_val_->setText(ps > 0
+ ? QString("%1x").arg(ps, 0, 'f', 1)
+ : QStringLiteral("—"));
+ }
+
+ // Graham Number = sqrt(22.5 * EPS * BookValue)
+ // EPS ≈ (market_cap / shares_outstanding) / pe_ratio (approximate)
+ if (graham_val_) {
+ double eps = (last_info_.pe_ratio > 0 && last_info_.current_price > 0)
+ ? last_info_.current_price / last_info_.pe_ratio : 0.0;
+ double bv = last_info_.book_value;
+ double graham = (eps > 0 && bv > 0) ? std::sqrt(22.5 * eps * bv) : 0.0;
+ graham_val_->setText(graham > 0
+ ? fmt_currency(graham)
+ : QStringLiteral("—"));
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Display helpers
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::display_dcf_result(const QJsonValue& data) {
+ auto obj = data.toObject();
+ // Try common response key names from QuantLib API
+ double intrinsic = obj.value("intrinsic_value_per_share").toDouble(0.0);
+ if (intrinsic == 0.0)
+ intrinsic = obj.value("intrinsic_value").toDouble(0.0);
+ if (intrinsic == 0.0)
+ intrinsic = obj.value("value_per_share").toDouble(0.0);
+
+ if (intrinsic_val_)
+ intrinsic_val_->setText(intrinsic > 0 ? fmt_currency(intrinsic) : QStringLiteral("—"));
+
+ if (current_price_ <= 0 || intrinsic <= 0) return;
+
+ double margin_pct = (intrinsic - current_price_) / current_price_ * 100.0;
+ QString margin_text = QString("%1%2%")
+ .arg(margin_pct >= 0 ? "+" : "")
+ .arg(margin_pct, 0, 'f', 1);
+
+ if (margin_val_) {
+ margin_val_->setText(margin_text);
+ QString col = margin_pct > 10 ? QString(ui::colors::POSITIVE()) :
+ margin_pct < -10 ? QString(ui::colors::NEGATIVE()) :
+ QString(ui::colors::AMBER());
+ margin_val_->setStyleSheet(
+ QString("color:%1; font-size:14px; font-weight:700;").arg(col));
+ }
+
+ if (verdict_badge_) {
+ if (margin_pct > 20)
+ set_badge(verdict_badge_, tr("UNDERVALUED"), ui::colors::POSITIVE());
+ else if (margin_pct < -20)
+ set_badge(verdict_badge_, tr("OVERVALUED"), ui::colors::NEGATIVE());
+ else
+ set_badge(verdict_badge_, tr("FAIRLY VALUED"), ui::colors::AMBER());
+ }
+}
+
+void EquityValuationTab::display_altman_result(const QJsonValue& data) {
+ auto obj = data.toObject();
+ double z = obj.value("z_score").toDouble(
+ obj.value("altman_z_score").toDouble(0.0));
+
+ if (altman_val_)
+ altman_val_->setText(QString::number(z, 'f', 2));
+
+ if (altman_badge_) {
+ if (z > 2.99)
+ set_badge(altman_badge_, tr("SAFE ZONE"), ui::colors::POSITIVE());
+ else if (z >= 1.81)
+ set_badge(altman_badge_, tr("GREY ZONE"), ui::colors::AMBER());
+ else
+ set_badge(altman_badge_, tr("DISTRESS ZONE"), ui::colors::NEGATIVE());
+ }
+}
+
+void EquityValuationTab::display_piotroski_result(const QJsonValue& data) {
+ auto obj = data.toObject();
+ int f = obj.value("f_score").toInt(
+ obj.value("piotroski_f_score").toInt(-1));
+
+ if (piotroski_val_)
+ piotroski_val_->setText(f >= 0 ? QString("%1/9").arg(f) : QStringLiteral("—"));
+
+ if (piotroski_badge_ && f >= 0) {
+ if (f >= 8)
+ set_badge(piotroski_badge_, tr("STRONG (%1-9)").arg(f), ui::colors::POSITIVE());
+ else if (f >= 5)
+ set_badge(piotroski_badge_, tr("NEUTRAL (%1-7)").arg(f), ui::colors::AMBER());
+ else
+ set_badge(piotroski_badge_, tr("WEAK (0-%1)").arg(f), ui::colors::NEGATIVE());
+ }
+}
+
+void EquityValuationTab::display_beneish_result(const QJsonValue& data) {
+ auto obj = data.toObject();
+ double m = obj.value("m_score").toDouble(
+ obj.value("beneish_m_score").toDouble(0.0));
+
+ if (beneish_val_)
+ beneish_val_->setText(QString::number(m, 'f', 2));
+
+ if (beneish_badge_) {
+ if (m < -2.22)
+ set_badge(beneish_badge_, tr("UNLIKELY MANIPULATOR"), ui::colors::POSITIVE());
+ else
+ set_badge(beneish_badge_, tr("POSSIBLE MANIPULATOR"), ui::colors::NEGATIVE());
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Utility
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::clear_results() {
+ auto reset = [](QLabel* l) { if (l) l->setText(QStringLiteral("—")); };
+ auto clear_badge = [](QLabel* l) { if (l) l->setText(QString()); };
+
+ reset(intrinsic_val_);
+ reset(current_price_val_);
+ reset(margin_val_);
+ clear_badge(verdict_badge_);
+ reset(altman_val_);
+ clear_badge(altman_badge_);
+ reset(piotroski_val_);
+ clear_badge(piotroski_badge_);
+ reset(beneish_val_);
+ clear_badge(beneish_badge_);
+ reset(ev_ebitda_val_);
+ reset(ev_revenue_val_);
+ reset(price_sales_val_);
+ reset(graham_val_);
+}
+
+void EquityValuationTab::set_badge(QLabel* badge, const QString& text, const QString& hex_color) {
+ if (!badge) return;
+ badge->setText(text);
+ badge->setStyleSheet(QString(
+ "background:%1; color:#000000; padding:2px 10px;"
+ " border-radius:3px; font-size:10px; font-weight:700;")
+ .arg(hex_color));
+}
+
+QString EquityValuationTab::fmt_currency(double value) const {
+ QString cs = QStringLiteral("$");
+ if (current_currency_ == QStringLiteral("INR")) cs = QStringLiteral("₹");
+ else if (current_currency_ == QStringLiteral("EUR")) cs = QStringLiteral("€");
+ else if (current_currency_ == QStringLiteral("GBP")) cs = QStringLiteral("£");
+ return QString("%1%2").arg(cs).arg(value, 0, 'f', 2);
+}
+
+double EquityValuationTab::get_stmt_val(
+ const QVector<QPair<QString, QJsonObject>>& stmt,
+ const QString& key, int period_idx) const
+{
+ if (period_idx >= stmt.size()) return 0.0;
+ return stmt[period_idx].second.value(key).toDouble(0.0);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// i18n
+// ─────────────────────────────────────────────────────────────────────────────
+
+void EquityValuationTab::changeEvent(QEvent* e) {
+ if (e->type() == QEvent::LanguageChange) {
+ for (auto it = i18n_labels_.begin(); it != i18n_labels_.end(); ++it)
+ it.key()->setText(tr(it.value()));
+ if (calc_btn_) calc_btn_->setText(tr("CALCULATE"));
+ }
+ QWidget::changeEvent(e);
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquityValuationTab.h b/fincept-qt/src/screens/equity_research/EquityValuationTab.h
new file mode 100644
index 000000000..7e26e7d9b
--- /dev/null
+++ b/fincept-qt/src/screens/equity_research/EquityValuationTab.h
@@ -0,0 +1,112 @@
+// src/screens/equity_research/EquityValuationTab.h
+#pragma once
+
+#include "services/equity/EquityResearchModels.h"
+
+#include <QDoubleSpinBox>
+#include <QHash>
+#include <QLabel>
+#include <QPointer>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QWidget>
+
+#include <cmath>
+
+class QFrame;
+class QVBoxLayout;
+class QHBoxLayout;
+class QGroupBox;
+
+namespace fincept::screens {
+
+class EquityValuationTab : public QWidget {
+ Q_OBJECT
+public:
+ explicit EquityValuationTab(QWidget* parent = nullptr);
+
+ // Called by EquityResearchScreen when symbol changes
+ void set_symbol(const QString& symbol);
+
+ // Called by EquityResearchScreen::on_info_loaded()
+ void set_stock_info(const services::equity::StockInfo& info);
+
+ // Called by EquityResearchScreen::on_financials_loaded()
+ void set_financials(const services::equity::FinancialsData& data);
+
+protected:
+ void changeEvent(QEvent* e) override;
+
+private slots:
+ void on_calculate_clicked();
+
+private:
+ // ── UI builders ──────────────────────────────────────────────
+ void build_ui();
+ void build_dcf_section(QVBoxLayout* parent);
+ void build_scoring_section(QVBoxLayout* parent);
+ void build_multiples_section(QVBoxLayout* parent);
+
+ // ── Data helpers ─────────────────────────────────────────────
+ void pre_fill_dcf_inputs();
+ void clear_results();
+ void run_scoring_models();
+ void run_multiples();
+
+ // ── Result display ───────────────────────────────────────────
+ void display_dcf_result(const QJsonValue& data);
+ void display_altman_result(const QJsonValue& data);
+ void display_piotroski_result(const QJsonValue& data);
+ void display_beneish_result(const QJsonValue& data);
+ void display_multiples_result(const QJsonValue& data);
+
+ // ── Formatting helpers ────────────────────────────────────────
+ void set_badge(QLabel* badge, const QString& text, const QString& hex_color);
+ QString fmt_currency(double value) const;
+ QString fmt_num(double value, int decimals = 2) const;
+ double get_stmt_val(const QVector<QPair<QString, QJsonObject>>& stmt,
+ const QString& key, int period_idx = 0) const;
+
+ // ── DCF inputs ───────────────────────────────────────────────
+ QDoubleSpinBox* fcf_input_ = nullptr; // Free cash flow (millions)
+ QDoubleSpinBox* growth_input_ = nullptr; // Near-term growth %
+ QDoubleSpinBox* terminal_input_ = nullptr; // Terminal growth %
+ QDoubleSpinBox* discount_input_ = nullptr; // Discount rate / WACC %
+ QDoubleSpinBox* years_input_ = nullptr; // Projection years
+ QDoubleSpinBox* shares_input_ = nullptr; // Shares outstanding (millions)
+ QPushButton* calc_btn_ = nullptr;
+
+ // ── DCF result labels ─────────────────────────────────────────
+ QLabel* intrinsic_val_ = nullptr;
+ QLabel* current_price_val_ = nullptr;
+ QLabel* margin_val_ = nullptr;
+ QLabel* verdict_badge_ = nullptr;
+
+ // ── Scoring labels ────────────────────────────────────────────
+ QLabel* altman_val_ = nullptr;
+ QLabel* altman_badge_ = nullptr;
+ QLabel* piotroski_val_ = nullptr;
+ QLabel* piotroski_badge_ = nullptr;
+ QLabel* beneish_val_ = nullptr;
+ QLabel* beneish_badge_ = nullptr;
+ QLabel* scoring_note_ = nullptr; // "Load financials first" hint
+
+ // ── Multiples labels ──────────────────────────────────────────
+ QLabel* ev_ebitda_val_ = nullptr;
+ QLabel* price_sales_val_ = nullptr;
+ QLabel* ev_revenue_val_ = nullptr;
+ QLabel* graham_val_ = nullptr;
+
+ // ── State ─────────────────────────────────────────────────────
+ QString current_symbol_;
+ double current_price_ = 0.0;
+ QString current_currency_ = QStringLiteral("USD");
+ services::equity::StockInfo last_info_;
+ services::equity::FinancialsData last_financials_;
+ bool financials_loaded_ = false;
+
+ // i18n: label → translatable source string
+ QHash<QLabel*, const char*> i18n_labels_;
+};
+
+} // namespace fincept::screens