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/ai_quant_lab/QuantModulePanel_Common.h
//
// Private header -- included only by QuantModulePanel*.cpp translation units.
// Provides cross-panel helpers that were originally in file-static anonymous
// namespaces inside QuantModulePanel.cpp. Several panel families (GS Quant,
// Functime, Statsmodels, Fortitudo, Gluonts, Quant Reporting) share the same
// numeric-input parsing and synthetic-sample generators, so they live here.
#pragma once
#include <QCoreApplication>
#include <QDate>
#include <QJsonArray>
#include <QPushButton>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QWidget>
#include <cmath>
namespace fincept::screens::quant_common {
// Enable / disable every "run" button of a panel. make_run_button() tags them all with the
// objectName "quantRunButton". Used to keep a second click from launching a duplicate Python
// process (a second multi-minute training run, a second RD-Agent task) while one is in flight.
inline void set_run_buttons_enabled(QWidget* panel, bool enabled) {
const bool retrain_busy = panel->property("rrBusy").toBool();
for (auto* b : panel->findChildren<QPushButton*>(QStringLiteral("quantRunButton"))) {
// A rolling retrain in flight keeps its own launch buttons disabled (see set_retrain_busy).
if (enabled && retrain_busy && b->property("rrRetrain").toBool())
continue;
b->setEnabled(enabled);
}
}
// Rolling retrain has several launch buttons (the Execute tab and one "Run Now" per schedule card)
// that share one in-flight state, kept as a property on the panel so cards rebuilt mid-run come
// up disabled too. Buttons opt in by carrying the "rrRetrain" property.
inline void set_retrain_busy(QWidget* panel, bool busy) {
panel->setProperty("rrBusy", busy);
for (auto* b : panel->findChildren<QPushButton*>())
if (b->property("rrRetrain").toBool())
b->setEnabled(!busy);
}
// Parse a CSV / whitespace / newline string into a JSON array of doubles.
// Returns false on any non-numeric token (sets bad_token to the offender).
inline bool parse_doubles(const QString& text, QJsonArray& out, QString* bad_token = nullptr) {
out = QJsonArray{};
QString s = text;
static const QRegularExpression seps(R"([,;\t\n\r])");
s.replace(seps, " ");
const QStringList parts = s.split(' ', Qt::SkipEmptyParts);
bool ok = false;
for (const QString& p : parts) {
const double v = p.toDouble(&ok);
if (!ok) {
if (bad_token)
*bad_token = p;
return false;
}
out.append(v);
}
return true;
}
// Validate a JSON 2-D numeric matrix: every row an array of `cols` numbers
// (cols < 0: take the first row's width). Returns "" when valid, otherwise a
// user-facing reason. Ragged rows / strings used to reach the Python side and
// come back as an unrelated numpy traceback.
inline QString check_numeric_matrix(const QJsonArray& rows, int cols = -1) {
const auto tr_ = [](const char* s) { return QCoreApplication::translate("QuantModulePanel", s); };
if (rows.isEmpty())
return tr_("The matrix is empty.");
const int want = cols >= 0 ? cols : static_cast<int>(rows.first().toArray().size());
for (int r = 0; r < rows.size(); ++r) {
if (!rows.at(r).isArray())
return tr_("Row %1 is not an array.").arg(r + 1);
const QJsonArray row = rows.at(r).toArray();
if (row.size() != want)
return tr_("Row %1 has %2 values; expected %3.").arg(r + 1).arg(row.size()).arg(want);
for (const auto& v : row)
if (!v.isDouble())
return tr_("Row %1 contains a non-numeric value.").arg(r + 1);
}
return {};
}
// Split a comma-separated string into a JSON array of trimmed, non-empty
// strings. Replaces the ad-hoc `for (auto& s : text.split(',')) arr.append(...)`
// loops that shipped `[""]` to Python when the field was left blank.
inline QJsonArray parse_csv_strings(const QString& text, bool lowercase = false) {
QJsonArray out;
for (const QString& part : text.split(',', Qt::SkipEmptyParts)) {
const QString t = part.trimmed();
if (!t.isEmpty())
out.append(lowercase ? t.toLower() : t);
}
return out;
}
// Validate an OPTIONAL free-text YYYY-MM-DD date range. Blank fields are
// allowed (the Python side then picks its own defaults) but garbage is not --
// those used to be forwarded verbatim and blew up inside Qlib.
// Returns an empty QString on success; otherwise a user-facing message.
// iso_start / iso_end receive the normalised values (empty when left blank).
inline QString check_iso_range(const QString& start_text, const QString& end_text, QString& iso_start,
QString& iso_end) {
const auto tr_ = [](const char* s) { return QCoreApplication::translate("QuantModulePanel", s); };
iso_start.clear();
iso_end.clear();
const QString s = start_text.trimmed();
const QString e = end_text.trimmed();
QDate ds, de;
if (!s.isEmpty()) {
ds = QDate::fromString(s, QStringLiteral("yyyy-MM-dd"));
if (!ds.isValid())
return tr_("Start date must be YYYY-MM-DD (got '%1').").arg(s);
iso_start = ds.toString(QStringLiteral("yyyy-MM-dd"));
}
if (!e.isEmpty()) {
de = QDate::fromString(e, QStringLiteral("yyyy-MM-dd"));
if (!de.isValid())
return tr_("End date must be YYYY-MM-DD (got '%1').").arg(e);
iso_end = de.toString(QStringLiteral("yyyy-MM-dd"));
}
if (ds.isValid() && de.isValid() && ds > de)
return tr_("Start date (%1) is after end date (%2).").arg(iso_start, iso_end);
return {};
}
// Generate a small synthetic returns sample so the user can try the panel
// without typing 252 numbers. Produces ~1y of plausible daily returns.
inline QString sample_returns(unsigned seed = 1, int n = 252, double mu = 0.0005, double sigma = 0.012) {
quint32 state = seed ? seed : 1u;
auto rand01 = [&]() -> double {
state = state * 1664525u + 1013904223u;
return double(state >> 8) / double(1u << 24);
};
QStringList out;
out.reserve(n);
for (int i = 0; i < n; ++i) {
const double u1 = std::max(rand01(), 1e-12);
const double u2 = rand01();
constexpr double kTwoPi = 6.283185307179586;
const double z = std::sqrt(-2.0 * std::log(u1)) * std::cos(kTwoPi * u2);
out << QString::number(mu + sigma * z, 'f', 6);
}
return out.join(',');
}
// Synthetic time series sample with trend + seasonality + noise.
// Useful for the LOAD SAMPLE buttons on the Functime / Statsmodels / Gluonts panels.
inline QString sample_series(unsigned seed = 1, int n = 200, double base = 50.0, double trend_per_step = 0.05,
double season_amp = 5.0, int season_period = 30, double noise_sigma = 1.5) {
quint32 state = seed ? seed : 1u;
auto rand01 = [&]() -> double {
state = state * 1664525u + 1013904223u;
return double(state >> 8) / double(1u << 24);
};
QStringList out;
out.reserve(n);
for (int i = 0; i < n; ++i) {
const double u1 = std::max(rand01(), 1e-12);
const double u2 = rand01();
constexpr double kTwoPi = 6.283185307179586;
const double z = std::sqrt(-2.0 * std::log(u1)) * std::cos(kTwoPi * u2);
const double v = base + trend_per_step * i +
season_amp * std::sin(kTwoPi * double(i) / double(std::max(2, season_period))) +
noise_sigma * z;
out << QString::number(v, 'f', 4);
}
return out.join(',');
}
// Trending random walk -- useful for stationarity testing where d=1 should win.
inline QString sample_random_walk(unsigned seed = 1, int n = 150, double drift = 0.05, double sigma = 1.0) {
quint32 state = seed ? seed : 1u;
auto rand01 = [&]() -> double {
state = state * 1664525u + 1013904223u;
return double(state >> 8) / double(1u << 24);
};
QStringList out;
out.reserve(n);
double level = 0.0;
for (int i = 0; i < n; ++i) {
const double u1 = std::max(rand01(), 1e-12);
const double u2 = rand01();
constexpr double kTwoPi = 6.283185307179586;
const double z = std::sqrt(-2.0 * std::log(u1)) * std::cos(kTwoPi * u2);
level += drift + sigma * z;
out << QString::number(level, 'f', 4);
}
return out.join(',');
}
} // namespace fincept::screens::quant_common