feat(cpp/datascience): CPU stats + MCMC primitives
Nuevo dominio cpp/functions/datascience con primitivas puras CPU para post- proceso de samples Monte Carlo y diagnostico de cadenas MCMC. Diseñadas como gemelas CPU de los kernels GPU (rng pareja con gpu_rng_glsl, MH 1D/ND con mc_metropolis_hastings_gpu) para validar numericamente y para datasets pequeños donde el dispatch GPU no compensa. - rng: xoshiro256++ con uniform / normal (Box-Muller) / below (Lemire) / categorical. Determinista bit-exacto dado seed. - stats_summary: sum (Kahan), mean, var/std (Welford one-pass), min, max, quantile / percentile (R type-7). - autocorr: r(k), ACF, tau_int (Sokal) — diagnostico ACF y ESS. - rhat_ess: Gelman-Rubin clasico y split + ESS basico (multi-chain). - beta_dist: lgamma (Lanczos), beta_pdf, beta_cdf (continued fraction), beta_quantile, mean/var/std — para inferencia Beta-Binomial. - drawdown: max_dd absoluto/pct + underwater series para sesiones simuladas y backtests. - samples_to_grid_2d: binning 2D CPU para alimentar heatmap_cpp_viz / contour_cpp_viz desde samples (x[], y[]). - metropolis_hastings: MH 1D y ND con target log-pdf como std::function (no normalizada). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
#include "datascience/drawdown.h"
|
||||
|
||||
namespace fn::ds {
|
||||
|
||||
DrawdownResult drawdown_max(const double* equity, std::size_t n) {
|
||||
DrawdownResult r{};
|
||||
if (equity == nullptr || n == 0) return r;
|
||||
|
||||
double peak = equity[0];
|
||||
std::size_t peak_i = 0;
|
||||
double max_dd = 0.0;
|
||||
std::size_t best_peak_i = 0;
|
||||
std::size_t best_trough_i = 0;
|
||||
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
double v = equity[i];
|
||||
if (v > peak) {
|
||||
peak = v;
|
||||
peak_i = i;
|
||||
} else {
|
||||
double dd = peak - v;
|
||||
if (dd > max_dd) {
|
||||
max_dd = dd;
|
||||
best_peak_i = peak_i;
|
||||
best_trough_i = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
r.max_dd = max_dd;
|
||||
r.peak_idx = best_peak_i;
|
||||
r.trough_idx = best_trough_i;
|
||||
double peak_value = equity[best_peak_i];
|
||||
if (peak_value > 0.0) {
|
||||
r.max_dd_pct = max_dd / peak_value;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
void drawdown_series(const double* equity, std::size_t n, double* out) {
|
||||
if (equity == nullptr || out == nullptr || n == 0) return;
|
||||
double peak = equity[0];
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
if (equity[i] > peak) peak = equity[i];
|
||||
out[i] = peak - equity[i];
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace fn::ds
|
||||
Reference in New Issue
Block a user