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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
// src/screens/equity_research/EquityOverviewTab.cpp
#include "screens/equity_research/EquityOverviewTab.h"
#include "services/equity/EquityResearchService.h"
#include "ui/theme/Theme.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QEvent>
#include <QFile>
#include <QFrame>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
#include <QPainter>
#include <QScrollArea>
#include <QSizePolicy>
#include <QTextStream>
#include <QVBoxLayout>
#include <algorithm>
#include <cmath>
namespace fincept::screens {
// ── Accent colors without a theme token ──────────────────────────────────────
static constexpr const char* CYAN = "#22d3ee";
static constexpr const char* YELLOW = "#eab308";
static constexpr const char* PURPLE = "#a855f7";
static constexpr const char* BLUE = "#3b82f6";
static constexpr const char* MAGENTA = "#e879f9";
static constexpr int FONT_KEY = 12; // key labels
static constexpr int FONT_VAL = 13; // value labels
static constexpr int FONT_TITLE = 12; // panel titles
static constexpr int FONT_DESC = 12; // description text
namespace {
// The inline error banner is owned by the content layout rather than by a
// member pointer (the tab's header is out of scope for this change), so it is
// addressed by object name.
constexpr const char* kErrorBannerName = "overviewErrorBanner";
constexpr const char* kErrorMessageName = "overviewErrorMessage";
constexpr const char* kRetryButtonName = "overviewRetryButton";
/// Show the inline error banner with `message`, or hide it when `message` is
/// empty. Modelled on MarketPanel::show_error + its [RETRY] affordance.
void set_overview_error(QWidget* tab, const QString& message) {
auto* banner = tab->findChild<QFrame*>(QLatin1String(kErrorBannerName));
if (!banner)
return;
if (auto* label = tab->findChild<QLabel*>(QLatin1String(kErrorMessageName)))
label->setText(message);
banner->setVisible(!message.isEmpty());
}
} // namespace
// Panel + row helpers live on the class so they can register the title and
// key labels with the per-instance translation map. Each call site passes a
// stable English source string declared via QT_TR_NOOP so lupdate sees it.
QFrame* EquityOverviewTab::make_panel_(const char* title_key, const char* title_color) {
auto* f = new QFrame;
f->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;border-radius:2px;}")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
auto* vl = new QVBoxLayout(f);
vl->setContentsMargins(10, 7, 10, 7);
vl->setSpacing(4);
if (title_key && title_key[0]) {
auto* lbl = new QLabel(tr(title_key));
lbl->setStyleSheet(QString("color:%1;font-size:%2px;font-weight:700;"
"letter-spacing:1px;background:transparent;border:0;")
.arg(title_color)
.arg(FONT_TITLE));
vl->addWidget(lbl);
i18n_labels_.insert(lbl, title_key);
auto* sep = new QFrame;
sep->setFrameShape(QFrame::HLine);
sep->setFixedHeight(1);
sep->setStyleSheet(QString("border:0;background:%1;").arg(ui::colors::BORDER_DIM()));
vl->addWidget(sep);
}
return f;
}
QLabel* EquityOverviewTab::add_row_(QFrame* panel, const char* key, const char* val_color) {
auto* hl = new QHBoxLayout;
hl->setSpacing(4);
hl->setContentsMargins(0, 0, 0, 0);
auto* k = new QLabel(tr(key));
k->setStyleSheet(QString("color:%1;font-size:%2px;background:transparent;border:0;")
.arg(ui::colors::TEXT_SECONDARY())
.arg(FONT_KEY));
i18n_labels_.insert(k, key);
auto* v = new QLabel(QString::fromUtf8("\xe2\x80\x94"));
v->setStyleSheet(QString("color:%1;font-size:%2px;font-weight:600;background:transparent;border:0;")
.arg(val_color)
.arg(FONT_VAL));
v->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
hl->addWidget(k);
hl->addWidget(v, 1);
static_cast<QVBoxLayout*>(panel->layout())->addLayout(hl);
return v;
}
// ══════════════════════════════════════════════════════════════════════════════
// ResearchCandleCanvas — QPainter candlestick chart
// ══════════════════════════════════════════════════════════════════════════════
ResearchCandleCanvas::ResearchCandleCanvas(QWidget* parent) : QWidget(parent) {
setMinimumHeight(250);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void ResearchCandleCanvas::set_candles(const QVector<services::equity::Candle>& candles, const QString& cs) {
candles_ = candles;
currency_sym_ = cs;
dirty_ = true;
update();
}
void ResearchCandleCanvas::clear() {
candles_.clear();
dirty_ = true;
update();
}
void ResearchCandleCanvas::resizeEvent(QResizeEvent* e) {
QWidget::resizeEvent(e);
dirty_ = true;
}
void ResearchCandleCanvas::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange) {
// Empty-state text ("Waiting for data...") is drawn directly by
// paintEvent — invalidate the cache so it repaints in the new locale.
dirty_ = true;
update();
}
QWidget::changeEvent(event);
}
void ResearchCandleCanvas::paintEvent(QPaintEvent*) {
if (dirty_) {
rebuild_cache();
dirty_ = false;
}
QPainter p(this);
p.drawPixmap(0, 0, cache_);
}
void ResearchCandleCanvas::rebuild_cache() {
const int W = width();
const int H = height();
if (W <= 0 || H <= 0)
return;
cache_ = QPixmap(W, H);
cache_.fill(QColor(ui::colors::BG_BASE()));
QPainter p(&cache_);
p.setRenderHint(QPainter::Antialiasing, false);
const int total = candles_.size();
if (total == 0) {
p.setPen(QColor(ui::colors::TEXT_SECONDARY()));
p.setFont(QFont("Consolas", 11));
p.drawText(cache_.rect(), Qt::AlignCenter, tr("Waiting for data..."));
return;
}
const int start = qMax(0, total - MAX_VISIBLE);
const int count = total - start;
// Price range
double lo = 1e18, hi = 0.0;
for (int i = start; i < total; ++i) {
lo = std::min(lo, candles_[i].low);
hi = std::max(hi, candles_[i].high);
}
if (lo >= hi)
return;
const double margin = (hi - lo) * 0.06;
lo -= margin;
hi += margin;
const int plot_w = W - PRICE_AXIS_W;
const int plot_h = H - TIME_AXIS_H;
if (plot_w <= 0 || plot_h <= 0)
return;
auto py = [&](double price) -> int { return static_cast<int>(plot_h - (price - lo) / (hi - lo) * plot_h); };
// Grid lines
p.setPen(QPen(QColor(ui::colors::BORDER_DIM()), 1, Qt::DotLine));
for (int g = 1; g < 6; ++g) {
int gy = plot_h * g / 6;
p.drawLine(0, gy, plot_w, gy);
}
// Candles
const double slot_w = static_cast<double>(plot_w) / count;
const int body_w = qMax(1, static_cast<int>(slot_w * 0.65));
const int half = body_w / 2;
const QColor bull_color(ui::colors::POSITIVE.get());
const QColor bear_color(ui::colors::NEGATIVE.get());
const QColor wick_bull("#2a9d5c");
const QColor wick_bear("#b83a3a");
for (int i = 0; i < count; ++i) {
const auto& c = candles_[start + i];
const int cx = static_cast<int>((i + 0.5) * slot_w);
const bool bull = c.close >= c.open;
const QColor& col = bull ? bull_color : bear_color;
const QColor& wcol = bull ? wick_bull : wick_bear;
const int open_y = py(c.open);
const int close_y = py(c.close);
const int high_y = py(c.high);
const int low_y = py(c.low);
const int body_top = std::min(open_y, close_y);
const int body_bot = std::max(open_y, close_y);
const int body_h = qMax(1, body_bot - body_top);
// Wick
p.setPen(QPen(wcol, 1));
p.drawLine(cx, high_y, cx, body_top);
p.drawLine(cx, body_bot, cx, low_y);
// Body
p.fillRect(cx - half, body_top, body_w, body_h, col);
}
// Price axis (right)
p.setPen(QPen(QColor(ui::colors::BORDER_DIM.get()), 1));
p.drawLine(plot_w, 0, plot_w, plot_h);
QFont lbl_font("Consolas", 9);
p.setFont(lbl_font);
QFontMetrics fm(lbl_font);
p.setPen(QColor(ui::colors::TEXT_SECONDARY.get()));
const bool is_large = hi > 1000;
for (int g = 0; g <= 6; ++g) {
double price = lo + (hi - lo) * g / 6.0;
int gy = py(price);
QString txt = currency_sym_ + (is_large ? QString::number(price, 'f', 0) : QString::number(price, 'f', 2));
p.drawText(plot_w + 6, gy + fm.ascent() / 2, txt);
}
// Time axis (bottom)
p.setPen(QPen(QColor(ui::colors::BORDER_DIM.get()), 1));
p.drawLine(0, plot_h, plot_w, plot_h);
p.setPen(QColor(ui::colors::TEXT_SECONDARY.get()));
const qint64 span_sec = candles_.last().timestamp - candles_.first().timestamp;
const int label_step = qMax(1, count / 8);
for (int i = 0; i < count; i += label_step) {
const auto& c = candles_[start + i];
QDateTime dt = QDateTime::fromSecsSinceEpoch(c.timestamp);
QString label;
if (span_sec > 365LL * 86400)
label = dt.toString("MMM yy");
else if (span_sec > 60LL * 86400)
label = dt.toString("dd MMM");
else
label = dt.toString("dd MMM");
int lx = static_cast<int>((i + 0.5) * slot_w);
int tw = fm.horizontalAdvance(label);
if (lx - tw / 2 > 0 && lx + tw / 2 < plot_w)
p.drawText(lx - tw / 2, plot_h + TIME_AXIS_H - 4, label);
}
// Last candle close price line (highlight)
if (!candles_.isEmpty()) {
double last_close = candles_.last().close;
int ly = py(last_close);
p.setPen(QPen(QColor(ui::colors::AMBER.get()), 1, Qt::DashLine));
p.drawLine(0, ly, plot_w, ly);
}
}
// ══════════════════════════════════════════════════════════════════════════════
// EquityOverviewTab
// ══════════════════════════════════════════════════════════════════════════════
EquityOverviewTab::EquityOverviewTab(QWidget* parent) : QWidget(parent) {
build_ui();
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::quote_loaded, this, &EquityOverviewTab::on_quote_loaded);
connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityOverviewTab::on_info_loaded);
connect(&svc, &services::equity::EquityResearchService::historical_loaded, this,
&EquityOverviewTab::on_historical_loaded);
// Overview waits on three legs (quote / info / historical) and only hides the
// overlay on success, so any one failing left "LOADING OVERVIEW…" spinning
// over the tab with no way to dismiss it. Hiding the overlay fixed the spin
// but discarded the reason, leaving a blank tab that explained nothing — so
// render the message inline with a retry, the way MarketPanel does.
connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
[this](const QString& ctx, const QString& message) {
if (ctx != QLatin1String("Quote") && ctx != QLatin1String("Info") &&
ctx != QLatin1String("Historical"))
return;
if (loading_overlay_)
loading_overlay_->hide_loading();
// Legs that never arrived for THIS symbol must not keep showing the previous
// symbol's figures behind the banner — blank them (the legs that did land stay).
if (!info_loaded_)
render_info(services::equity::StockInfo{});
if (!quote_loaded_) {
const QString dash = QString::fromUtf8("\xe2\x80\x94");
for (auto* lbl : {open_val_, high_val_, low_val_, prev_close_val_, vol_val_})
lbl->setText(dash);
}
if (!historical_loaded_)
rebuild_chart({});
const QString detail = message.trimmed();
set_overview_error(this, detail.isEmpty() ? tr("%1 data could not be loaded.").arg(ctx)
: tr("%1 data could not be loaded: %2").arg(ctx, detail));
});
}
void EquityOverviewTab::set_symbol(const QString& symbol) {
if (symbol == current_symbol_)
return;
current_symbol_ = symbol;
info_loaded_ = quote_loaded_ = historical_loaded_ = false;
set_overview_error(this, QString()); // drop the previous symbol's failure
loading_overlay_->show_loading(tr("LOADING OVERVIEW…"));
// The tab is handed its symbol only when shown, so it asks for every leg it renders
// (a cached copy answers at once; a request the header bar already started is shared).
// Candles follow the period button that is currently selected.
auto& svc = services::equity::EquityResearchService::instance();
svc.load_quote_only(symbol);
svc.load_info_only(symbol);
svc.load_historical_only(symbol, current_period_);
}
// ── Build UI ──────────────────────────────────────────────────────────────────
void EquityOverviewTab::build_ui() {
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
loading_overlay_ = new ui::LoadingOverlay(this);
auto* scroll = new QScrollArea;
scroll->setWidgetResizable(true);
scroll->setFrameShape(QFrame::NoFrame);
scroll->setStyleSheet("background:transparent;border:0;");
scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
auto* content = new QWidget(this);
content->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
auto* vl = new QVBoxLayout(content);
vl->setContentsMargins(8, 8, 8, 8);
vl->setSpacing(6);
// ── Inline error banner (hidden until a load leg fails) ───────────────────
// Built from make_panel_/add_row_ so it inherits the tab's panel styling and
// registers its title + key with i18n_labels_ for retranslation; the retry
// button picks up the global QSS QPushButton rule. It sits above the panels
// rather than replacing them, so a partial load (quote arrived, history
// failed) still shows the data that did land.
auto* error_banner = make_panel_(QT_TR_NOOP("DATA UNAVAILABLE"), ui::colors::NEGATIVE);
error_banner->setObjectName(QLatin1String(kErrorBannerName));
auto* error_msg = add_row_(error_banner, QT_TR_NOOP("REASON"), ui::colors::NEGATIVE);
error_msg->setObjectName(QLatin1String(kErrorMessageName));
error_msg->setWordWrap(true); // service messages are full sentences
error_msg->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
auto* retry_btn = new QPushButton(tr("[RETRY]"));
retry_btn->setObjectName(QLatin1String(kRetryButtonName));
retry_btn->setCursor(Qt::PointingHandCursor);
retry_btn->setAccessibleName(tr("Retry loading the overview tab"));
connect(retry_btn, &QPushButton::clicked, this, [this]() {
if (current_symbol_.isEmpty())
return;
set_overview_error(this, QString());
info_loaded_ = quote_loaded_ = historical_loaded_ = false;
if (loading_overlay_)
loading_overlay_->show_loading(tr("LOADING OVERVIEW…"));
services::equity::EquityResearchService::instance().load_symbol(current_symbol_, current_period_);
});
static_cast<QVBoxLayout*>(error_banner->layout())->addWidget(retry_btn, 0, Qt::AlignLeft);
error_banner->setVisible(false);
vl->addWidget(error_banner);
auto* top = new QHBoxLayout;
top->setSpacing(6);
auto* col1 = build_col1();
col1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
col1->setFixedWidth(220);
auto* chart = build_chart_panel();
chart->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
auto* col4 = build_col4();
col4->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
col4->setFixedWidth(220);
top->addWidget(col1);
top->addWidget(chart, 1);
top->addWidget(col4);
vl->addLayout(top, 1);
vl->addWidget(build_bottom_row(), 0);
scroll->setWidget(content);
auto* outer = new QVBoxLayout(this);
outer->setContentsMargins(0, 0, 0, 0);
outer->addWidget(scroll);
}
// ── Column 1: Trading + Valuation + Share Stats ───────────────────────────────
QWidget* EquityOverviewTab::build_col1() {
auto* w = new QWidget(this);
auto* vl = new QVBoxLayout(w);
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(6);
vl->addWidget(build_trading_panel());
vl->addWidget(build_valuation_panel());
vl->addWidget(build_share_stats_panel());
return w;
}
QWidget* EquityOverviewTab::build_trading_panel() {
auto* p = make_panel_(QT_TR_NOOP("TODAY'S TRADING"), ui::colors::AMBER);
open_val_ = add_row_(p, QT_TR_NOOP("OPEN"), CYAN);
high_val_ = add_row_(p, QT_TR_NOOP("HIGH"), ui::colors::POSITIVE);
low_val_ = add_row_(p, QT_TR_NOOP("LOW"), ui::colors::NEGATIVE);
prev_close_val_ = add_row_(p, QT_TR_NOOP("PREV CLOSE"), ui::colors::TEXT_PRIMARY);
vol_val_ = add_row_(p, QT_TR_NOOP("VOLUME"), YELLOW);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_valuation_panel() {
auto* p = make_panel_(QT_TR_NOOP("VALUATION"), CYAN);
mktcap_val_ = add_row_(p, QT_TR_NOOP("MARKET CAP"), CYAN);
pe_val_ = add_row_(p, QT_TR_NOOP("P/E RATIO"), YELLOW);
fwd_pe_val_ = add_row_(p, QT_TR_NOOP("FWD P/E"), YELLOW);
peg_val_ = add_row_(p, QT_TR_NOOP("PEG RATIO"), YELLOW);
pb_val_ = add_row_(p, QT_TR_NOOP("P/B RATIO"), CYAN);
div_val_ = add_row_(p, QT_TR_NOOP("DIV YIELD"), ui::colors::POSITIVE);
beta_val_ = add_row_(p, QT_TR_NOOP("BETA"), ui::colors::TEXT_PRIMARY);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_share_stats_panel() {
auto* p = make_panel_(QT_TR_NOOP("SHARE STATS"), PURPLE);
shares_out_val_ = add_row_(p, QT_TR_NOOP("SHARES OUT"), CYAN);
float_val_ = add_row_(p, QT_TR_NOOP("FLOAT"), CYAN);
insiders_val_ = add_row_(p, QT_TR_NOOP("INSIDERS"), YELLOW);
institutions_val_ = add_row_(p, QT_TR_NOOP("INSTITUTIONS"), YELLOW);
short_pct_val_ = add_row_(p, QT_TR_NOOP("SHORT %"), ui::colors::NEGATIVE);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
// ── Chart Panel ───────────────────────────────────────────────────────────────
QWidget* EquityOverviewTab::build_chart_panel() {
auto* p = new QFrame;
p->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;border-radius:2px;}")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
auto* vl = new QVBoxLayout(p);
vl->setContentsMargins(8, 6, 8, 6);
vl->setSpacing(4);
// Period buttons row
auto* btn_row = new QHBoxLayout;
btn_row->setSpacing(4);
btn_row->setContentsMargins(0, 0, 0, 0);
auto* period_lbl = new QLabel(tr("PERIOD"));
period_lbl->setStyleSheet(QString("color:%1;font-size:12px;font-weight:600;background:transparent;border:0;")
.arg(ui::colors::TEXT_SECONDARY()));
btn_row->addWidget(period_lbl);
i18n_labels_.insert(period_lbl, QT_TR_NOOP("PERIOD"));
auto btn_style_inactive =
QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"border-radius:2px;padding:3px 10px;font-size:12px;font-weight:700;font-family:'Consolas',monospace;}"
"QPushButton:hover{border-color:%3;background:%4;}")
.arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::AMBER(), ui::colors::BG_RAISED());
auto btn_style_active =
QString("QPushButton{background:%1;color:%2;border:1px solid %1;"
"border-radius:2px;padding:3px 10px;font-size:12px;font-weight:700;font-family:'Consolas',monospace;}")
.arg(ui::colors::AMBER(), ui::colors::BG_BASE());
auto make_btn = [&](const QString& label, QPushButton*& out, const QString& period) {
out = new QPushButton(label);
out->setCursor(Qt::PointingHandCursor);
out->setStyleSheet(period == current_period_ ? btn_style_active : btn_style_inactive);
connect(out, &QPushButton::clicked, this, [this, out, period]() { switch_period(out, period); });
btn_row->addWidget(out);
};
make_btn("1M", btn_1m_, "1mo");
make_btn("3M", btn_3m_, "3mo");
make_btn("6M", btn_6m_, "6mo");
make_btn("1Y", btn_1y_, "1y");
make_btn("5Y", btn_5y_, "5y");
active_period_btn_ = btn_1y_;
btn_row->addStretch();
vl->addLayout(btn_row);
// Chart widget — prefer KLineChart when WebEngine is available
#ifdef HAS_QT_WEBENGINE
kline_chart_ = new fincept::ui::KLineChartWidget;
if (kline_chart_->is_available()) {
vl->addWidget(kline_chart_, 1);
} else {
delete kline_chart_;
kline_chart_ = nullptr;
candle_canvas_ = new ResearchCandleCanvas;
vl->addWidget(candle_canvas_, 1);
}
#else
candle_canvas_ = new ResearchCandleCanvas;
vl->addWidget(candle_canvas_, 1);
#endif
return p;
}
void EquityOverviewTab::switch_period(QPushButton* btn, const QString& period) {
if (period == current_period_ && historical_loaded_)
return;
current_period_ = period;
// Update button styles
auto inactive =
QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"border-radius:2px;padding:3px 10px;font-size:12px;font-weight:700;font-family:'Consolas',monospace;}"
"QPushButton:hover{border-color:%3;background:%4;}")
.arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::AMBER(), ui::colors::BG_RAISED());
auto active =
QString("QPushButton{background:%1;color:%2;border:1px solid %1;"
"border-radius:2px;padding:3px 10px;font-size:12px;font-weight:700;font-family:'Consolas',monospace;}")
.arg(ui::colors::AMBER(), ui::colors::BG_BASE());
for (auto* b : {btn_1m_, btn_3m_, btn_6m_, btn_1y_, btn_5y_})
b->setStyleSheet(b == btn ? active : inactive);
active_period_btn_ = btn;
// Reload data with new period
if (!current_symbol_.isEmpty()) {
set_overview_error(this, QString()); // the previous period's failure no longer applies
// Only the candles depend on the period — quote + info are already on screen.
services::equity::EquityResearchService::instance().load_historical_only(current_symbol_, period);
}
}
// ── Column 4: Analyst + 52W + Profitability + Growth ─────────────────────────
QWidget* EquityOverviewTab::build_col4() {
auto* w = new QWidget(this);
auto* vl = new QVBoxLayout(w);
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(6);
vl->addWidget(build_analyst_panel());
vl->addWidget(build_52w_panel());
vl->addWidget(build_profitability_panel());
vl->addWidget(build_growth_panel());
return w;
}
QWidget* EquityOverviewTab::build_analyst_panel() {
auto* p = make_panel_(QT_TR_NOOP("ANALYST TARGETS"), MAGENTA);
target_high_val_ = add_row_(p, QT_TR_NOOP("HIGH"), ui::colors::POSITIVE);
target_mean_val_ = add_row_(p, QT_TR_NOOP("MEAN"), YELLOW);
target_low_val_ = add_row_(p, QT_TR_NOOP("LOW"), ui::colors::NEGATIVE);
analyst_count_val_ = add_row_(p, QT_TR_NOOP("ANALYSTS"), CYAN);
rec_key_label_ = new QLabel(QString::fromUtf8("\xe2\x80\x94"));
rec_key_label_->setAlignment(Qt::AlignCenter);
rec_key_label_->setStyleSheet(QString("background:%1;color:%2;border-radius:2px;padding:3px 8px;"
"font-size:12px;font-weight:700;")
.arg(ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY()));
static_cast<QVBoxLayout*>(p->layout())->addWidget(rec_key_label_);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_52w_panel() {
auto* p = make_panel_(QT_TR_NOOP("52 WEEK RANGE"), YELLOW);
w52h_val_ = add_row_(p, QT_TR_NOOP("HIGH"), ui::colors::POSITIVE);
w52l_val_ = add_row_(p, QT_TR_NOOP("LOW"), ui::colors::NEGATIVE);
avg_vol_val_ = add_row_(p, QT_TR_NOOP("AVG VOL"), CYAN);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_profitability_panel() {
auto* p = make_panel_(QT_TR_NOOP("PROFITABILITY"), ui::colors::POSITIVE);
gross_margin_val_ = add_row_(p, QT_TR_NOOP("GROSS MARGIN"), ui::colors::POSITIVE);
op_margin_val_ = add_row_(p, QT_TR_NOOP("OPER. MARGIN"), ui::colors::POSITIVE);
profit_margin_val_ = add_row_(p, QT_TR_NOOP("PROFIT MARGIN"), ui::colors::POSITIVE);
roa_val_ = add_row_(p, QT_TR_NOOP("ROA"), CYAN);
roe_val_ = add_row_(p, QT_TR_NOOP("ROE"), CYAN);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_growth_panel() {
auto* p = make_panel_(QT_TR_NOOP("GROWTH (LATEST QTR, YoY)"), BLUE);
rev_growth_val_ = add_row_(p, QT_TR_NOOP("REVENUE"), ui::colors::POSITIVE);
earnings_growth_val_ = add_row_(p, QT_TR_NOOP("EARNINGS"), ui::colors::POSITIVE);
// yfinance revenueGrowth / earningsGrowth compare the most recent quarter with the same
// quarter a year earlier — not annual or TTM growth.
p->setToolTip(tr("Most recent quarter vs the same quarter a year earlier (Yahoo Finance)"));
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
// ── Bottom Row ────────────────────────────────────────────────────────────────
QWidget* EquityOverviewTab::build_bottom_row() {
auto* w = new QWidget(this);
auto* hl = new QHBoxLayout(w);
hl->setContentsMargins(0, 0, 0, 0);
hl->setSpacing(6);
hl->addWidget(build_company_desc_panel(), 2);
auto* right = new QWidget(this);
auto* rvl = new QVBoxLayout(right);
rvl->setContentsMargins(0, 0, 0, 0);
rvl->setSpacing(6);
rvl->addWidget(build_company_info_panel());
rvl->addWidget(build_financial_health_panel());
hl->addWidget(right, 1);
return w;
}
QWidget* EquityOverviewTab::build_company_desc_panel() {
auto* p = make_panel_(QT_TR_NOOP("COMPANY OVERVIEW"), CYAN);
company_desc_ = new QLabel(QString::fromUtf8("\xe2\x80\x94"));
company_desc_->setWordWrap(true);
company_desc_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
company_desc_->setStyleSheet(QString("color:%1;font-size:%2px;line-height:1.5;"
"background:transparent;border:0;")
.arg(ui::colors::TEXT_PRIMARY())
.arg(FONT_DESC));
company_desc_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
static_cast<QVBoxLayout*>(p->layout())->addWidget(company_desc_);
return p;
}
QWidget* EquityOverviewTab::build_company_info_panel() {
auto* p = make_panel_(QT_TR_NOOP("COMPANY INFO"), ui::colors::TEXT_PRIMARY);
company_emp_ = add_row_(p, QT_TR_NOOP("EMPLOYEES"), CYAN);
company_web_ = add_row_(p, QT_TR_NOOP("WEBSITE"), BLUE);
company_currency_ = add_row_(p, QT_TR_NOOP("CURRENCY"), CYAN);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
QWidget* EquityOverviewTab::build_financial_health_panel() {
auto* p = make_panel_(QT_TR_NOOP("FINANCIAL HEALTH"), ui::colors::AMBER);
cash_val_ = add_row_(p, QT_TR_NOOP("CASH"), ui::colors::POSITIVE);
debt_val_ = add_row_(p, QT_TR_NOOP("DEBT"), ui::colors::NEGATIVE);
free_cf_val_ = add_row_(p, QT_TR_NOOP("FREE CF"), CYAN);
static_cast<QVBoxLayout*>(p->layout())->addStretch();
return p;
}
// ── Slots ─────────────────────────────────────────────────────────────────────
void EquityOverviewTab::on_quote_loaded(services::equity::QuoteData q) {
if (q.symbol != current_symbol_)
return;
cached_quote_ = q;
quote_loaded_ = true;
if (info_loaded_ && quote_loaded_ && historical_loaded_)
loading_overlay_->hide_loading();
open_val_->setText(fmt_price(q.open));
high_val_->setText(fmt_price(q.high));
low_val_->setText(fmt_price(q.low));
prev_close_val_->setText(fmt_price(q.prev_close));
vol_val_->setText(q.volume > 0.0 ? fmt_large(q.volume) : QString::fromUtf8("\xe2\x80\x94"));
}
void EquityOverviewTab::on_info_loaded(services::equity::StockInfo info) {
if (info.symbol != current_symbol_)
return;
cached_info_ = info;
info_loaded_ = true;
current_currency_ = info.currency;
if (info_loaded_ && quote_loaded_ && historical_loaded_)
loading_overlay_->hide_loading();
render_info(info);
}
// ── Render helper ─────────────────────────────────────────────────────────────
// Extracted from on_info_loaded so retranslateUi() can re-render every value
// label (currency-formatted prices, percentages, N/A fallbacks, the
// recommendation badge) without involving the service or the load flags.
void EquityOverviewTab::render_info(const services::equity::StockInfo& info) {
const QString na = QString::fromUtf8("â"); // missing → "—", never a made-up 0
// The info payload reports a field the source lacks as 0 — show N/A, not a made-up
// "0" / "0.00%" (shares, float, volumes and the balance-sheet snapshot included).
auto large_or_na = [&na](double v) { return v > 0.0 ? fmt_large(v) : na; };
auto pct_or_na = [&na](double v) { return v != 0.0 ? fmt_pct(v) : na; };
// Re-render quote and chart with correct currency
if (quote_loaded_) {
open_val_->setText(fmt_price(cached_quote_.open));
high_val_->setText(fmt_price(cached_quote_.high));
low_val_->setText(fmt_price(cached_quote_.low));
prev_close_val_->setText(fmt_price(cached_quote_.prev_close));
}
if (historical_loaded_ && !cached_candles_.isEmpty() && candle_canvas_) {
candle_canvas_->set_candles(cached_candles_,
currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_));
}
// Valuation
mktcap_val_->setText(info.market_cap > 0 ? fmt_large(info.market_cap) : na);
pe_val_->setText(info.pe_ratio > 0 ? QString::number(info.pe_ratio, 'f', 2) : na);
fwd_pe_val_->setText(info.forward_pe > 0 ? QString::number(info.forward_pe, 'f', 2) : na);
peg_val_->setText(info.peg_ratio > 0 ? QString::number(info.peg_ratio, 'f', 2) : na);
pb_val_->setText(info.price_to_book > 0 ? QString::number(info.price_to_book, 'f', 2) : na);
// yfinance (pinned 0.2.66) reports dividendYield already in percent (AAPL: 0.33 for
// 0.33%) while every other ratio here is a fraction, so fmt_pct()'s ×100 printed 33.00%.
div_val_->setText(info.dividend_yield > 0 ? fmt_pct(info.dividend_yield / 100.0) : na);
beta_val_->setText(info.beta != 0.0 ? QString::number(info.beta, 'f', 2) : na);
// Share Stats
shares_out_val_->setText(large_or_na(info.shares_outstanding));
float_val_->setText(large_or_na(info.float_shares));
insiders_val_->setText(pct_or_na(info.held_insiders_pct));
institutions_val_->setText(pct_or_na(info.held_institutions_pct));
short_pct_val_->setText(pct_or_na(info.short_pct_of_float));
// 52 Week Range
w52h_val_->setText(fmt_price(info.week52_high));
w52l_val_->setText(fmt_price(info.week52_low));
avg_vol_val_->setText(large_or_na(info.avg_volume));
// Analyst Targets
target_high_val_->setText(fmt_price(info.target_high));
target_mean_val_->setText(fmt_price(info.target_mean));
target_low_val_->setText(fmt_price(info.target_low));
analyst_count_val_->setText(info.analyst_count > 0 ? QString::number(info.analyst_count) : na);
// Recommendation badge — compare against the English API key, render the
// translated label. Key is server-side ("strong_buy"/"buy"/"hold"/...).
const QString rec_key = info.recommendation_key.toLower();
QString rec_text;
const char* rec_color = ui::colors::TEXT_SECONDARY;
if (rec_key == "strong_buy") {
rec_text = tr("STRONG BUY");
rec_color = ui::colors::POSITIVE;
} else if (rec_key == "buy") {
rec_text = tr("BUY");
rec_color = ui::colors::POSITIVE;
} else if (rec_key == "hold") {
rec_text = tr("HOLD");
rec_color = ui::colors::AMBER;
} else if (rec_key == "sell") {
rec_text = tr("SELL");
rec_color = ui::colors::NEGATIVE;
} else if (rec_key == "strong_sell") {
rec_text = tr("STRONG SELL");
rec_color = ui::colors::NEGATIVE;
}
rec_key_label_->setText(rec_text.isEmpty() ? QString::fromUtf8("\xe2\x80\x94") : rec_text);
rec_key_label_->setStyleSheet(QString("background:%1;color:%2;border-radius:2px;padding:3px 8px;"
"font-size:12px;font-weight:700;")
.arg(ui::colors::BG_RAISED(), rec_color));
// Profitability
gross_margin_val_->setText(pct_or_na(info.gross_margins));
op_margin_val_->setText(pct_or_na(info.operating_margins));
profit_margin_val_->setText(pct_or_na(info.profit_margins));
roa_val_->setText(pct_or_na(info.roa));
roe_val_->setText(pct_or_na(info.roe));
// Growth
rev_growth_val_->setText(pct_or_na(info.revenue_growth));
earnings_growth_val_->setText(pct_or_na(info.earnings_growth));
// Company Info
company_desc_->setText(info.description);
company_emp_->setText(info.employees > 0 ? fmt_large(static_cast<double>(info.employees)) : na);
company_web_->setText(info.website.left(40));
company_currency_->setText(info.currency.isEmpty() ? na : info.currency);
// Financial Health
cash_val_->setText(large_or_na(info.total_cash));
debt_val_->setText(large_or_na(info.total_debt));
free_cf_val_->setText(info.free_cashflow != 0.0 ? fmt_large(info.free_cashflow) : na);
}
void EquityOverviewTab::on_historical_loaded(QString symbol, QVector<services::equity::Candle> candles) {
if (symbol != current_symbol_)
return;
historical_loaded_ = true;
cached_candles_ = candles;
if (info_loaded_ && quote_loaded_ && historical_loaded_)
loading_overlay_->hide_loading();
rebuild_chart(candles);
}
void EquityOverviewTab::rebuild_chart(const QVector<services::equity::Candle>& candles) {
#ifdef HAS_QT_WEBENGINE
if (kline_chart_) {
if (candles.isEmpty()) {
// set_candles() ignores an empty series, which would leave the previous
// symbol's chart on screen — an empty result must actually clear it.
kline_chart_->clear();
return;
}
QJsonArray arr;
for (const auto& c : candles) {
QJsonObject obj;
obj[QStringLiteral("timestamp")] = static_cast<double>(c.timestamp);
obj[QStringLiteral("open")] = c.open;
obj[QStringLiteral("high")] = c.high;
obj[QStringLiteral("low")] = c.low;
obj[QStringLiteral("close")] = c.close;
obj[QStringLiteral("volume")] = static_cast<double>(c.volume);
arr.append(obj);
}
kline_chart_->set_candles(arr);
return;
}
#endif
const QString cs = currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_);
candle_canvas_->set_candles(candles, cs);
}
// ── Formatters ────────────────────────────────────────────────────────────────
QString EquityOverviewTab::fmt_large(double v) {
bool neg = v < 0;
double av = qAbs(v);
QString s;
if (av >= 1e12)
s = QString("%1T").arg(av / 1e12, 0, 'f', 2);
else if (av >= 1e9)
s = QString("%1B").arg(av / 1e9, 0, 'f', 2);
else if (av >= 1e6)
s = QString("%1M").arg(av / 1e6, 0, 'f', 2);
else if (av >= 1e3)
s = QString("%1K").arg(av / 1e3, 0, 'f', 1);
else
s = QString::number(static_cast<qint64>(av));
return neg ? "-" + s : s;
}
QString EquityOverviewTab::fmt_pct(double v) {
return QString("%1%").arg(v * 100.0, 0, 'f', 2);
}
QString EquityOverviewTab::currency_symbol(const QString& currency_code) {
static const QHash<QString, QString> map = {
{"USD", "$"},
{"EUR", "\xe2\x82\xac"},
{"GBP", "\xc2\xa3"},
{"JPY", "\xc2\xa5"},
{"CNY", "\xc2\xa5"},
{"INR", "\xe2\x82\xb9"},
{"KRW", "\xe2\x82\xa9"},
{"RUB", "\xe2\x82\xbd"},
{"BRL", "R$"},
{"TRY", "\xe2\x82\xba"},
{"CHF", "CHF "},
{"CAD", "C$"},
{"AUD", "A$"},
{"NZD", "NZ$"},
{"HKD", "HK$"},
{"SGD", "S$"},
{"TWD", "NT$"},
{"MXN", "MX$"},
{"ZAR", "R"},
{"SEK", "kr"},
{"NOK", "kr"},
{"DKK", "kr"},
{"PLN", "z\xc5\x82"},
{"THB", "\xe0\xb8\xbf"},
{"IDR", "Rp"},
{"MYR", "RM"},
{"PHP", "\xe2\x82\xb1"},
{"CZK", "K\xc4\x8d"},
{"HUF", "Ft"},
{"ILS", "\xe2\x82\xaa"},
{"CLP", "CL$"},
{"COP", "COL$"},
{"PEN", "S/."},
{"ARS", "AR$"},
{"EGP", "E\xc2\xa3"},
{"NGN", "\xe2\x82\xa6"},
{"PKR", "Rs"},
{"BDT", "\xe0\xa7\xb3"},
{"VND", "\xe2\x82\xab"},
{"SAR", "SR"},
{"QAR", "QR"},
{"AED", "AED "},
{"KWD", "KD"},
};
const auto it = map.find(currency_code.toUpper());
return (it != map.end()) ? it.value() : (currency_code + " ");
}
QString EquityOverviewTab::fmt_price(double v) const {
if (v == 0.0)
return QString::fromUtf8("\xe2\x80\x94");
const QString sym = current_currency_.isEmpty() ? "$" : currency_symbol(current_currency_);
return QString("%1%2").arg(sym).arg(v, 0, 'f', 2);
}
// ── Re-translation ───────────────────────────────────────────────────────────
//
// Two passes:
// 1. Walk the i18n_labels_ map and re-apply tr() to every registered panel
// title / row key. The map is populated by make_panel_ / add_row_ at
// construction time, keyed by stable English source strings.
// 2. Re-render the loaded info + quote so currency-formatted values, "N/A"
// fallbacks, and the recommendation badge pick up the new locale.
void EquityOverviewTab::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi();
}
QWidget::changeEvent(event);
}
void EquityOverviewTab::retranslateUi() {
for (auto it = i18n_labels_.constBegin(); it != i18n_labels_.constEnd(); ++it) {
it.key()->setText(tr(it.value()));
}
// The error banner's title + key ride the map above; its button does not.
if (auto* retry_btn = findChild<QPushButton*>(QLatin1String(kRetryButtonName))) {
retry_btn->setText(tr("[RETRY]"));
retry_btn->setAccessibleName(tr("Retry loading the overview tab"));
}
// Re-render whatever data is already loaded so value labels (which carry
// localized "N/A" / recommendation badges / currency-formatted numbers)
// pick up the new language without a service round-trip.
if (info_loaded_)
render_info(cached_info_);
if (quote_loaded_) {
open_val_->setText(fmt_price(cached_quote_.open));
high_val_->setText(fmt_price(cached_quote_.high));
low_val_->setText(fmt_price(cached_quote_.low));
prev_close_val_->setText(fmt_price(cached_quote_.prev_close));
vol_val_->setText(cached_quote_.volume > 0.0 ? fmt_large(cached_quote_.volume)
: QString::fromUtf8("\xe2\x80\x94"));
}
}
} // namespace fincept::screens