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/services/equity/EquityResearchService.h
#pragma once
#include "services/equity/EquityResearchModels.h"
#include <QHash>
#include <QObject>
#include <QTimer>
#include <functional>
class QNetworkAccessManager;
namespace fincept::services::equity {
/// News source for fetch_news(). Auto = the default GNews → Yahoo chain;
/// NewsApi = newsapi.org (only when a key is configured in Data Sources).
enum class NewsProvider { Auto, NewsApi };
class EquityResearchService : public QObject {
Q_OBJECT
public:
static EquityResearchService& instance();
// ── Async API — results delivered via signals ─────────────────────────────
void search_symbols(const QString& query);
void schedule_search(const QString& query); // debounced entry point
/// Fetches quote + info + historical in parallel (three Python calls).
/// Used by the UI panels that need all three. Tool handlers that only
/// need one slice should use the per-data loaders below to avoid wasting
/// daemon slots and Yahoo API calls.
void load_symbol(const QString& symbol, const QString& period = "1y");
/// Per-data loaders. Each fires exactly one Python call and emits the
/// matching *_loaded signal. Cache-aware: re-emits immediately on hit.
void load_quote_only(const QString& symbol);
void load_info_only(const QString& symbol);
void load_historical_only(const QString& symbol, const QString& period = "1y");
void fetch_financials(const QString& symbol);
void fetch_technicals(const QString& symbol, const QString& period = "1y");
void fetch_peers(const QString& symbol, const QStringList& peer_symbols);
/// `force` drops the cached result first, so a user-pressed REFRESH really re-fetches.
void fetch_news(const QString& symbol, int count = 20, NewsProvider provider = NewsProvider::Auto,
bool force = false);
/// The configured & enabled NewsAPI.org key from the Data Sources tab, or an
/// empty string when none. Used to gate the News-tab provider switch and to
/// supply the key at fetch time.
QString configured_newsapi_key() const;
/// One-shot OHLCV pull for the "Download price data (CSV)" dialog — any yfinance
/// period/interval (intraday included), never cached, never broadcast (one caller,
/// one result). `done(ok, candles, error)` runs on the service thread; `candles` is
/// ascending by time. Implemented in EquityResearchService_Ext.cpp.
using HistoryCallback = std::function<void(bool ok, QVector<Candle> candles, QString error)>;
void fetch_price_history(const QString& symbol, const QString& period, const QString& interval,
HistoryCallback done);
signals:
void search_results_loaded(QVector<fincept::services::equity::SearchResult> results);
void quote_loaded(fincept::services::equity::QuoteData quote);
void info_loaded(fincept::services::equity::StockInfo info);
void historical_loaded(QString symbol, QVector<fincept::services::equity::Candle> candles);
void financials_loaded(fincept::services::equity::FinancialsData data);
void technicals_loaded(fincept::services::equity::TechnicalsData data);
void peers_loaded(QVector<fincept::services::equity::PeerData> peers);
void news_loaded(QString symbol, QVector<fincept::services::equity::NewsArticle> articles);
void error_occurred(QString context, QString message);
private:
explicit EquityResearchService(QObject* parent = nullptr);
Q_DISABLE_COPY(EquityResearchService)
// ── Python helpers ────────────────────────────────────────────────────────
void run_python(const QString& script, const QStringList& args, std::function<void(bool, const QString&)> cb);
// Candle source: cache → region-matched connected broker → yfinance
// fallback. done(ok, hist_json) is invoked on the main thread.
void ensure_candles(const QString& symbol, const QString& period, std::function<void(bool, const QString&)> done);
// yfinance news path — the fallback fetch_news() uses when Google News
// (fetch_company_news.py) is unavailable or returns no articles.
void fetch_news_yfinance(const QString& symbol, int count);
// NewsAPI.org path (native HTTP via news_nam_). Used when the equity News tab
// selects the NewsApi provider and a key is configured. Caches under
// "equity:news:newsapi:<symbol>"; on any failure (401/quota/network/empty)
// it falls back to fetch_news(symbol, count, NewsProvider::Auto).
void fetch_news_newsapi(const QString& symbol, int count, const QString& api_key);
// ── Parsers ───────────────────────────────────────────────────────────────
QuoteData parse_quote(const QJsonObject& obj) const;
StockInfo parse_info(const QJsonObject& obj) const;
QVector<Candle> parse_candles(const QJsonArray& arr) const;
FinancialsData parse_financials(const QJsonObject& obj) const;
TechnicalsData parse_technicals(const QString& symbol, const QJsonArray& rows) const;
TechSignal score_indicator(const QString& name, double value, double sma20, double sma50) const;
QVector<PeerData> parse_peers(const QJsonArray& arr) const;
QVector<NewsArticle> parse_news(const QJsonArray& arr) const;
// ── Cache TTLs — delegated to CacheManager ───────────────────────────────
static constexpr int kQuoteTtlSec = 30;
static constexpr int kInfoTtlSec = 300;
static constexpr int kHistoricalTtlSec = 120;
static constexpr int kNewsTtlSec = 180;
static constexpr int kFinancialsTtlSec = 600; // statements only change quarterly
// Last-known-good statements: replayed (flagged stale) the moment a symbol is reopened
// after the 10-minute copy expired, while the refresh runs — and kept on screen, still
// flagged, if that refresh fails.
static constexpr int kFinancialsLkgTtlSec = 30 * 24 * 3600;
// Indicator values off DAILY bars; recomputing them on every Technicals-tab visit spawned
// a compute_technicals.py process each time.
static constexpr int kTechnicalsTtlSec = 300;
// ── Debounce ──────────────────────────────────────────────────────────────
static constexpr int kDebounceMs = 350;
QTimer* search_debounce_ = nullptr;
QString pending_query_;
// Dedicated NAM for third-party NewsAPI.org calls — kept separate from the
// Fincept-backend HttpClient singleton (which carries base-url/session token).
QNetworkAccessManager* news_nam_ = nullptr;
// In-flight guards: the Financials/Valuation tabs and the Sentiment blend all
// ask for the same symbol at about the same time, and each used to spawn its own
// Python process. A repeat request while one is running is dropped — the
// completion signal is broadcast to every listener anyway. Value = start time
// (ms since epoch); an entry older than kInflightMaxAgeMs is treated as lost so a
// callback that never fires cannot wedge the symbol forever.
QHash<QString, qint64> financials_inflight_;
QHash<QString, qint64> technicals_inflight_;
// Same folding for the header-bar/Overview/Analysis legs: the screen, the Overview tab
// and the Analysis tab each ask for the same quote/info/history when a symbol opens.
QHash<QString, qint64> quote_inflight_;
QHash<QString, qint64> info_inflight_;
QHash<QString, qint64> historical_inflight_;
static constexpr qint64 kInflightMaxAgeMs = 90'000;
};
} // namespace fincept::services::equity