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/economics/panels/EiaPanel.cpp
// EIA U.S. Energy Information Administration
//
// Two data sources with different commands and response shapes:
//
// WPSR (Weekly Petroleum Status Report) — NO API KEY NEEDED
// Command: get_petroleum <category>
// Response: { "success": true, "category": "...", "data": [...], "count": N }
// data[] rows: { "date": "YYYY-MM-DD", "category": "...", "table": "...",
// "symbol": "...", "value": 1.23, "source": "petroleum_status_report" }
//
// STEO (Short-Term Energy Outlook) — REQUIRES EIA_API_KEY
// Command: get_steo <table>
// Response: { "success": true, "table": "...", "data": [...] }
// data[] rows: { "date": "YYYY-MM", "symbol": "WTIPUUS", "title": "WTI Crude...",
// "value": 78.5, "units": "$/barrel", "table": "STEO-01: ...",
// "source": "short_term_energy_outlook" }
#include "screens/economics/panels/EiaPanel.h"
#include "core/logging/Logger.h"
#include "services/economics/EconomicsService.h"
#include "ui/theme/Theme.h"
#include <QDate>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QVBoxLayout>
namespace fincept::screens {
namespace {
static constexpr const char* kEiaScript = "eia_data.py";
static constexpr const char* kEiaSourceId = "eia";
static constexpr const char* kEiaColor = "#4CAF50"; // green
} // namespace
// ── WPSR categories (no API key needed, downloads public XLS)
static const QList<QPair<QString, QString>> kWpsrCategories = {
{"Balance Sheet", "balance_sheet"},
{"Inputs & Production", "inputs_and_production"},
{"Crude Petroleum Stocks", "crude_petroleum_stocks"},
{"Gasoline & Fuel Stocks", "gasoline_fuel_stocks"},
{"Gasoline by Sub-PADD", "total_gasoline_by_sub_padd"},
{"Distillate Fuel Oil Stocks", "distillate_fuel_oil_stocks"},
{"Imports", "imports"},
{"Imports by Country", "imports_by_country"},
{"Weekly Estimates", "weekly_estimates"},
{"Spot Prices (Crude/Gas/Heating Oil)", "spot_prices_crude_gas_heating"},
{"Spot Prices (Diesel/Jet/Propane)", "spot_prices_diesel_jet_fuel_propane"},
{"Retail Prices", "retail_prices"},
{"Refiner/Blender Net Production", "refiner_blender_net_production"},
};
// ── STEO tables (requires EIA_API_KEY)
static const QList<QPair<QString, QString>> kSteoTables = {
{"01 — US Energy Markets Summary", "01"}, {"02 — Nominal Energy Prices", "02"},
{"04a — Petroleum & Liquid Fuels", "04a"}, {"05a — Natural Gas Supply & Consumption", "05a"},
{"07a — US Electricity Industry Overview", "07a"}, {"09a — Macroeconomic Indicators & CO2", "09a"},
};
// ── Constructor ───────────────────────────────────────────────────────────────
EiaPanel::EiaPanel(QWidget* parent) : EconPanelBase(kEiaSourceId, kEiaColor, parent) {
build_base_ui(this);
connect(&services::EconomicsService::instance(), &services::EconomicsService::result_ready, this,
&EiaPanel::on_result);
}
void EiaPanel::activate() {
show_empty(tr("Select a data source and category, then click FETCH\n"
"Weekly Petroleum Status Report requires no API key\n"
"Short-Term Energy Outlook requires EIA_API_KEY env var"));
}
// ── Controls ──────────────────────────────────────────────────────────────────
void EiaPanel::build_controls(QHBoxLayout* thl) {
auto make_lbl = [](const QString& text) {
auto* l = new QLabel(text);
l->setObjectName(QStringLiteral("econCtrlLabel"));
return l;
};
source_combo_ = new QComboBox;
source_combo_->addItem(tr("Weekly Petroleum (WPSR)"), "wpsr");
source_combo_->addItem(tr("Short-Term Outlook (STEO)"), "steo");
source_combo_->setFixedHeight(26);
source_combo_->setMinimumWidth(200);
connect(source_combo_, &QComboBox::currentIndexChanged, this, &EiaPanel::on_source_changed);
category_combo_ = new QComboBox;
category_combo_->setFixedHeight(26);
category_combo_->setMinimumWidth(260);
// Populate with WPSR categories initially
for (const auto& c : kWpsrCategories)
category_combo_->addItem(c.first, c.second);
apikey_notice_ = new QLabel(tr("No API key needed"));
apikey_notice_->setStyleSheet(
QString("color:%1; font-size:9px; background:transparent;").arg(ui::colors::POSITIVE()));
thl->addWidget(source_lbl_ = make_lbl(tr("SOURCE")));
thl->addWidget(source_combo_);
thl->addWidget(category_lbl_ = make_lbl(tr("CATEGORY")));
thl->addWidget(category_combo_);
thl->addWidget(apikey_notice_);
}
void EiaPanel::on_source_changed(int index) {
category_combo_->clear();
if (index == 0) {
// WPSR
for (const auto& c : kWpsrCategories)
category_combo_->addItem(c.first, c.second);
apikey_notice_->setText(tr("No API key needed"));
apikey_notice_->setStyleSheet(
QString("color:%1; font-size:9px; background:transparent;").arg(ui::colors::POSITIVE()));
} else {
// STEO
for (const auto& t : kSteoTables)
category_combo_->addItem(t.first, t.second);
apikey_notice_->setText(tr("Requires EIA_API_KEY"));
apikey_notice_->setStyleSheet(notice_style());
}
}
// ── Fetch ─────────────────────────────────────────────────────────────────────
void EiaPanel::on_fetch() {
const QString source = source_combo_->currentData().toString();
const QString category = category_combo_->currentData().toString();
if (category.isEmpty()) {
show_empty(tr("Select a category"));
return;
}
if (source == "wpsr") {
show_loading(tr("Fetching EIA Petroleum Report: %1…\n"
"(Downloads public XLS file — may take a few seconds)")
.arg(category_combo_->currentText()));
services::EconomicsService::instance().execute(kEiaSourceId, kEiaScript, "get_petroleum", {category},
"eia_wpsr_" + category);
} else {
show_loading(tr("Fetching EIA STEO Table %1…").arg(category_combo_->currentText()));
services::EconomicsService::instance().execute(kEiaSourceId, kEiaScript, "get_steo", {category},
"eia_steo_" + category);
}
}
// ── Result ────────────────────────────────────────────────────────────────────
void EiaPanel::on_result(const QString& request_id, const services::EconomicsResult& result) {
if (result.source_id != kEiaSourceId)
return;
if (!result.success) {
// Detect API key error for STEO
if (result.error.contains("API key") || result.error.contains("api_key")) {
show_error(tr("EIA API key not configured.\n"
"Set EIA_API_KEY environment variable.\n"
"Free key at: www.eia.gov/opendata/register.php"));
} else {
show_error(result.error);
}
return;
}
// Both WPSR and STEO return { "success": true, "data": [...] }
QJsonArray rows = result.data["data"].toArray();
if (rows.isEmpty()) {
show_empty(tr("No data returned for this selection"));
return;
}
// WPSR rows: { date, category, table, symbol, value, source }
// STEO rows: { date, symbol, title, value, units, table, source }
// Both have "date" and "value" — base display() handles both correctly.
// For WPSR, promote "symbol" as a useful column; for STEO "title" is descriptive.
// The base display() auto-detects date→col0, value→col1, rest follows.
SeriesMeta meta;
if (request_id.startsWith(QLatin1String("eia_steo_"))) {
// The Short-Term Energy Outlook is a forecast: months after the current one are EIA projections.
// Flag them per row so a projected price is never read as a reported one.
const QString this_month = QDate::currentDate().toString(QStringLiteral("yyyy-MM"));
QJsonArray flagged;
for (const auto& rv : std::as_const(rows)) {
QJsonObject r = rv.toObject();
r["status"] = r.value("date").toString().left(7) > this_month ? tr("EIA forecast") : tr("History");
flagged.append(r);
}
rows = flagged;
meta.note = tr("STEO: months after %1 are EIA forecasts").arg(this_month);
meta.source = tr("U.S. EIA — Short-Term Energy Outlook");
} else {
meta.source = tr("U.S. EIA — Weekly Petroleum Status Report");
meta.frequency = tr("Weekly");
}
set_series_meta(meta);
// Title from the request ("eia_<wpsr|steo>_<category>"), not the combo the user may have changed.
const QString category = request_id.section(QLatin1Char('_'), 2);
QString label = category;
for (const auto& c : kWpsrCategories)
if (c.second == category)
label = c.first;
for (const auto& t : kSteoTables)
if (t.second == category)
label = t.first;
const QString title = "EIA: " + label;
display(rows, title);
LOG_INFO("EiaPanel", QString("Displayed %1 rows — %2").arg(rows.size()).arg(request_id));
}
// ── i18n ──────────────────────────────────────────────────────────────────────
void EiaPanel::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange)
retranslateUi();
EconPanelBase::changeEvent(event);
}
void EiaPanel::retranslateUi() {
if (source_lbl_)
source_lbl_->setText(tr("SOURCE"));
if (category_lbl_)
category_lbl_->setText(tr("CATEGORY"));
if (source_combo_ && source_combo_->count() >= 2) {
source_combo_->setItemText(0, tr("Weekly Petroleum (WPSR)"));
source_combo_->setItemText(1, tr("Short-Term Outlook (STEO)"));
}
// API-key notice depends on the active source.
if (apikey_notice_ && source_combo_)
apikey_notice_->setText(source_combo_->currentIndex() == 0 ? tr("No API key needed")
: tr("Requires EIA_API_KEY"));
EconPanelBase::retranslateUi();
}
} // namespace fincept::screens